CSS

CSS Selector: Nth-Child, First-Child

Say we have html structure like this:

<div id="parent">
  <h1></h1>
  <p></p>
  <p></p>
</div>

What would this selector have selected?

#parent{
  p:first-child{}
}

Interestingly: nothing.

The selector above doesn’t mean “select the first p tag under #parent div”, but “select the first child under #parent div, if it’s a p tag”. And the description doesn’t fit anything. If we want to select the first p tag under a div, we might as well write this if we know the index:

#parent{
  >:nth-child(2){}
  p:nth-child(2){}
}

Or simply wrap all the p tags in a parent div of their own.

Weird behaviour of CSS selectors, to be paid attention to.

Standard