0

i am curious to know how the nth-child css selector works. I was expecting the following code to change the background color for the 3rd

element, that is "The third paragraph". However, when I run this code, the 2nd

element is getting selected and "The second paragraph" has a changed background color.

<html>
<head>
<style> 
p:nth-child(3) {
    background: #ff0000;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>

</body>
</html>

3 Answers 3

3

Since <p> is not a child of any ancestor and it cordially counts <h1>, you need to use :nth-of-type to target the third paragraph

p:nth-of-type(3) {
    background: #ff0000;
}

Fiddle

Sign up to request clarification or add additional context in comments.

Comments

1

nth-child does not care for the type of the other elements, so it also counts the h1 element.

You can archive what you want using p:nth-of-type(3)

EDIT: Clarification

1 Comment

I hope this makes it a little clearer what I meant :)
0

In this case, you're specifying a paragraph that is the nth-child of it's parent. Since the parent is body, and you're asking for n to be 3, it will be the second p in your markup.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.