Jack Jack - 2 years ago 76
HTML Question

Why does a p:nth-child(1) selector not select the first paragraph if there is a heading before it?

I know that this may seem like a very simple question, but I can't seem to wrap my mind around this concept. Why is it that I have to use the number "2" for the

selector to select the first paragraph? I'm confused because the number "2" selects the first paragraph after the header, but 1 selects nothing. If I were to remove the header, however, then I could select the first paragraph using the number "1."


<!DOCTYPE html>
p:nth-child(2) {
color: green;
<h1>This is a heading.</h1>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>

Answer Source

As @Harry said, h1 is the first child of its parent.

So when you do p:nth-child(1) { }, it wont works because the first p element is in second place, the h1 is in first place.

h1:nth-child(1){ } will works in that case.

You can also use p:first-of-type { } to select the first p of its parent.

See this fiddle with first-of-type example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download