The first/last/only/nth-child selector

Trying to understand the role of the space between an element and the colon that’s part of the pseudo-selector.

p: first-child
Selects all p elements that are the first child of some parent element.

p:first-child
Selects all first child elements that are nested under p.

Two questions:

  1. Is that correct?
  2. Does that apply to all the pseudo-selectors (first/last/only/nth)

Hey there @roisql :grinning:

Not entirely, but your close.

p:first-child selects every <p> element that is the first child nested under it’s parent element:

p:first-child {
  color: green
}
<div>
  <p> I will be green, I am the first child </p>
  <p> I won't be green, I am not the first child </p>
</div>

<div>
  <p> I will also be green, I am the first child of MY parent </p>
  <p> I am not the first child of my parent </p>
</div>

<div>
  <h1> Not green. Though I am a first child I am not a p element </h1>
  <p> I will not be green, I am not the first child </p>
<div>

I am guessing you meant p :first-child :thinking:
I don’t believe p: first-child is a valid selector.

If you have the selector p :first-child, than the first child of every <p> element will be selected:

<p> This text is not selected 
  <span> Though this is </span> 
  <span> yet this is not </span>
</p>

Not all pseudo selectors work exactly like this, for example p :hover does nothing.
However if you combine multiple selectors you can get some interesting results.

For example:

p :first-child:hover {
  color: green;
}

This will make the first child of every <p> element turn green when it is hovered over.

I would say the best way to learn about them is to experiment with them your self.

1 Like

Thank you! That was very helpful.

1 Like