Aiswarya Prakasan
Aiswarya Prakasan

Reputation: 1

nth-child selector in css

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>

Upvotes: 0

Views: 380

Answers (3)

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

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

Upvotes: 3

kinakuta
kinakuta

Reputation: 9037

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.

Upvotes: 0

edave
edave

Reputation: 188

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

Upvotes: 1

Related Questions