eirikrl
eirikrl

Reputation: 438

CSS First-child bug? or intended behavior?

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?

Upvotes: 1

Views: 278

Answers (2)

BoltClock
BoltClock

Reputation: 723789

While #two is the first child of #one but #three isn't, #three is still the first child of #two. So both inner divs get the styles.

The descendant combinator (the space character) in your selector tells the browser to select any div in any level of nesting from .test, as long as it's contained somewhere within an element with that class. The :first-child pseudo-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 >:

.test > div:first-child {}

Because > expresses a parent-child relationship, it is safe to imply that the parent concerned by div:first-child is represented by .test.

Upvotes: 8

mingos
mingos

Reputation: 24502

This is the intended behaviour. You need to write your CSS rule like this:

.test > div:first-child

The > ensures only the first child of the .test element is selected. Without it, any div that is the first child of any node within .test is selected.

Upvotes: 1

Related Questions