Jack Jack - 7 months ago 9
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

p:nth-child()
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."

HTML

<!DOCTYPE html>
<html>
<head>
<style>
p:nth-child(2) {
color: green;
}
</style>
</head>
<body>
<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>
</body>
</html>

Answer

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