Reputation: 1543
I'm trying to learn on Codecademy how to use nth-childs correctly. It says that
p:nth-child(2) {
color: red;
}
Would turn every paragraph that is the second child of its parent element red.
So I thought it meant that
body:nth-child(2) {
color: red;
}
<body>
<p> some text </p>
<p> some text </p>
</body>
Would mean that the second paragraph would turn red. But that doesn't work... What am I doing wrong?
Upvotes: 2
Views: 3892
Reputation: 1829
Second child of any parent, body, div or ay other container.
example:
<!doctype html>
<html>
<head>
<title>
Bla!
</title>
<style type='text/css'>
div:nth-child(2) { background-color:red; }
</style>
</head>
<body>
<div> First child (normal)
<div> first child of first child (normal) </div>
<div> Second child of first child (red) </div>
<div> Third child of first child (normal) </div>
</div>
<div> 2 Second child (red) </div>
<div> 3 Third child (normal) </div>
</body>
</html>
Upvotes: 0
Reputation: 5108
With
body:nth-child(2) {
color: red;
}
you are selecting the second body element which is simply not there, if you want to get the second p element in body you have to write:
body p:nth-child(2) {
color: red;
}
Upvotes: 3
Reputation: 26989
body:nth-child(2) {
color: red;
}
In the above code you are pointing to 2nd body of the page which is not possible.
Upvotes: -1
Reputation: 160083
:nth-child
applies to the element, not the children of the element. body:nth-child(2)
should be read as "every body
element which is the second child of it's parent", not "every element (*
) which is the second child of the body
element".
Use body > p:nth-child(2)
if you want to style a the second p
tag that is a direct decedent of the body
element.
Upvotes: 6