CSS first-child not working

Viewed 7445

Facing a weird problem

For the HTML:

<ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
    <li class="has-item">four</li>
    <li>five</li>
</ul>

This works:

ul li:first-child {
  font-size:30px
}

but why doesn't this

ul li.has-item:first-child {
  font-size:8px
}

Fiddle: https://jsfiddle.net/xx9us2sg/1/

1 Answers

The :first-child pseudo class, like all other :nth-child()-related pseudo-classes counts all siblings (i.e., elements having the same parent). Classes are ignored, as they have nothing to do with the DOM structure.

So :first-child is always the first sibling.

This...

ul li.has-item:first-child {
  font-size:8px
}

doesn't work because .has-item doesn't represent the :first-child of anything. The first child will always be <li>one</li>.

Related: Why is nth-child selector not working?

Related