Select first child of a div that has a container

I have the following html:

<form action="">
  <div class="cont">
    <div class="form-group">
      <input type="text">
      </div>
      </div>
      <div class="cont">
      <div class="form-group">
      <input type="text">
      </div>
      </div>
      <div class="cont">
      <div class="form-group">
      <input type="text">
    </div>
  </div>
</form>

I would like to select only the first form group.

This is easily achievable when .form-group is not contained by .cont, working example here.

I’ve been trying with what’s below and similar things:

form .cont .form-group:first-child{
  outline: 1px solid red;
}

I understand why this doesn’t work, easily visualized here.

Here’s a live explample., how can I select only the first form group?


solution

Based on your HTML in the second example, you could select the first .form-group element in the first .cont element:

Updated Example

form .cont:first-child .form-group:first-child {
  outline: 1px solid red;
}

If there aren’t multiple .form-group elements nested in the .cont element, like in your third example, you could omit the :first-child pseudo class from the .form-group element:

Updated Example

form .cont:first-child .form-group {
  outline: 1px solid red;
}

Of course, this won’t work in all instances, such as when the first .cont element doesn’t contain a .form-group element. It’s worth pointing out that your selector form .cont .form-group:first-child wasn’t working because the .form-group elements aren’t sibling children elements.