Combinator selectors – child, next sibling, and subsequent sibling
Sometimes you want to do something particular to an element but only if it follows another, or perhaps only if it is the child of another element. We are going to look now at how we can do that.
I’m making the assumption at this point that you understand the basic selector pattern where one class followed by another selects any descendant that matches. For example,.parent .descendant {}
would select any element that was a descendant of the .parent
element with a class of .descendant
, no matter how many levels deep.
The child combinator
The child combinator only selects direct descendants. Consider this markup:
<div class="parent">
<div class="descendant child">
<div class="descendant grandchild"></div>
</div>
</div>
We can select only the direct “child” of the parent element, like this...