baltoro baltoro - 27 days ago 10
CSS Question

Why didn't CSS adjacent combinator did not work here?

Can someone help me understand why adjacent combinator (+) below isn't working as the commented part of css.

Adjacent combinator (+) should match second selector

.btn
if it immediately follows the first selector i.e.
.btn-group
according to https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors and so I was expecting my first btn's background to change to blue.

<div class="btn-group">
<button class="btn">
Save
</button>

<button class="btn">
Revert
</button>
</div>

/* .btn-group .btn:first-child {
background-color: blue;
color: white;
} */

.btn-group + .btn {
background-color: blue;
color: white;
}

Answer Source

The adjacent sibling combinator (+) only targets the immediately preceding sibling element, not child element. This can be seen in the following:

.btn-group + .btn {
  background-color: blue;
  color: white;
}
<div class="btn-group">
  <button class="btn">
    Save
  </button>

  <button class="btn">
    Revert
  </button>
</div>

<button class="btn">
  Target
</button>

If you want to target the very first child, then you do indeed need to use .btn-group .btn:first-child. You can add in the child combinator (>) to increase specificity if required, with .btn-group > .btn:first-child:

span {
  background-color: red;
}

/* Higher specificity with the child combinator */
.btn-group > .btn:first-child {
  background-color: blue;
  color: white;
}
<div class="btn-group">
  <button class="btn">
    Save
    <span class="btn">Sub-class</span>
  </button>

  <button class="btn">
    Revert
  </button>
</div>

Adding the child combinator avoids any descendants other than children also having the rule applied to them as well, which can be confusing in combination with the pseudo-selector :first-child, as demonstrated in the following example:

span {
  background-color: red;
}

/* Higher specificity without the child combinator */
.btn-group .btn:first-child {
  background-color: blue;
  color: white;
}
<div class="btn-group">
  <button class="btn">
    Save
    <span class="btn">Sub-class</span>
  </button>

  <button class="btn">
    Revert
  </button>
</div>

Hope this helps! :)