nth-child selector in css

两盒软妹~` 提交于 2019-12-11 19:59:00

问题


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>

回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/26093889/nth-child-selector-in-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!