CSS Combinator Selectors

Combinator selectors are one of the things that always gets mixed up in my head, because their symbols and syntax are pretty abstract, in my opinion. For example, I tend to mix up the plus, + combinator selector with the tilda, ~ combinator selector. So, in this post I am going to go over how each combinator selector works, along with an example CodePen.

Both Classes combinator

This combinator applies styles to every HTML element that has BOTH of the classes in the selector. So, one HTML element has to have both classes for the styling to work.

  .plum.lightsalmon { ... }
  <p class="plum"></p>
  <p class="lightsalmon"></p>
  <p class="plum lightsalmon"></p>

General Sibling combinator

This combinator applies styles to every HTML element with the class lightsalmon that comes AFTER an HTML element with the class of plum.

  .plum ~ .lightsalmon  { ... }
  <p class="lightsalmon"></p>
  <p class="plum"></p>
  <p class="lightsalmon"></p>
  <p class="plum"></p>
  <p class="lightsalmon"></p>
  <p class="plum lightsalmon"></p>

Descendant combinator

This combinator applies styles to every HTML element that has the class lightsalmon and is INSIDE of the HTML element with the class plum.

  .plum .lightsalmon { ... }
  <div class="plum">
    <p class="lightsalmon"></p>
    <div class="seashell">
      <p class="lightsalmon"></p>
    </div>
    <p class="lightsalmon"></p>
  </div>
  <p class="lightsalmon"></p> // won't apply styles to this element
  <p class="plum"></p>

Adjacent Sibling combinator

This combinator applies styles to every HTML element that has the class lightsalmon and IMMEDIATELY FOLLOWS every HTML element with the class plum.

  .plum + .lightsalmon { ... }
  <div class="lightsalmon"></div>
  <div class="plum"></div>
  <div class="lightsalmon"></div>
  <div class="seashell"></div>
  <div class="lightsalmon"></div> // won't apply styles to this element

Child combinator

This combinator applies styles to every HTML element that has the class lightsalmon and is IMMEDIATELY INSIDE of the HTML element with the class plum.

.plum > .lightsalmon
  <div class="plum">
    <p class="lightsalmon"></p>
    <div class="seashell">
      <p class="lightsalmon"></p> // won't apply styles to this element
    </div>
    <p class="lightsalmon"></p>
  </div>
  <p class="lightsalmon"></p> // won't apply styles to this element
  <p class="plum"></p>

More Info

For more information on CSS selectors, CSS Tricks has a great almanac of all the different selectors, with links to articles explaining each one. Interneting is Hard also has a really good article that goes over common CSS selectors that includes code and visual examples.