3

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/

Fahad Sohail
  • 1,818
  • 4
  • 21
  • 33
  • 1
    The fault is, that your `li` with the class `has-item` is not the `first-child` of the `ul`. – DomeTune Oct 06 '17 at 14:02
  • if li:first-child selects the first-child of ul with type li then why doesn't li.has-item:first-child select the first child of ul with type li class .first-item – Fahad Sohail Oct 06 '17 at 14:05
  • @FahadSohail Because that's not how `:first-child` works. See the link I posted above. – TylerH Oct 06 '17 at 14:10
  • You missunderstand the `first-child` selector. The `first-child` selector, selects the first child of the parent. In this case the parent is `ul` and [Here is an Example of what i mean](https://jsfiddle.net/xx9us2sg/5/) – DomeTune Oct 06 '17 at 14:17

1 Answers1

6

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?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701