在css中的第n个子选择器 [英] nth-child selector in css

查看:113
本文介绍了在css中的第n个子选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道第n个子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>


推荐答案

由于< p& 不是任何祖先的子代,并且亲切地计数< h1> ,您需要使用 :nth-​​of-type 指定第三段

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;
}

这篇关于在css中的第n个子选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆