I have the following set up
.test div:first-child {};
<div class="test" id="one">
<div id="two">
<div id="three">
</div>
</div>
</div>
Somehow div#three inherits the first-child styles, even though it is not the first-child of div.test. Is this intentional by the browsers? Can someone explain this?
While
#twois the first child of#onebut#threeisn’t,#threeis still the first child of#two. So both innerdivs get the styles.The descendant combinator (the space character) in your selector tells the browser to select any
divin any level of nesting from.test, as long as it’s contained somewhere within an element with that class. The:first-childpseudo-class says to only select an element if it’s the first child of its parent, whatever that parent may be, not just the element represented on the left side of the combinator.If you only want to target the first child of
.test, use the child combinator>:Because
>expresses a parent-child relationship, it is safe to imply that the parent concerned bydiv:first-childis represented by.test.