[英]div's :nth-child(2) background-color is also changing body background-color
:nth-child(2)
为什么也会更改<body>
的颜色? 设置为1或3时不会发生这种情况。
代码( http://codepen.io/kreitzo/pen/mPXzWv ):
body { font-size: 50px; text-align: center; } div { width: 30px; height: 30px; background-color: red; } :nth-child(1) { background-color: blue; } :nth-child(2) { background-color: green; } :nth-child(3) { background-color: yellow; }
<div></div> <div></div> <div></div> <div></div>
这是因为body
标记是其父标记的第二个子标记(这是html
根标记)。 您可以在下面的屏幕截图中看到它。 html
标签的第一个孩子是head
标签,第二个孩子是body
标签。
选择器:nth-child(2)
选择作为其父级第二个子级的每个元素。
:nth-child(3)
, nth-child(1)
选择器不会影响body
的背景颜色,因为body
不是其父级的第三个或第一个子级。
如果您只想选择特定父级的第二个子级,则还应将父级作为选择器的一部分提及(如下所示):
body :nth-child(2)
-在body
下的任何级别选择作为其各自父级的第二body :nth-child(2)
所有元素。 因此,这将不会选择body
标签。 body > :nth-child(2)
-选择作为其各自父级的第二body > :nth-child(2)
所有元素,并且父级本身是body
标签的直接子级。 如果您只想选择第二个孩子的特定类型,则还应该在选择器中的伪类之前指定元素类型。 例如, div:nth-child(2)
将仅选择div
标签,这些标签是其各自父级的第二个子级。
因为body
是您html页面的第二个元素
结构是这样的
<html>
<head>
</head>
<body>
</body>
</html>
因此,您当前的CSS将捕获所有第二个元素。 像这样为div的元素定义css
body {
font-size: 50px;
text-align: center;
}
div {
width: 30px;
height: 30px;
background-color: red;
}
div:nth-child(1) {
background-color: blue;
}
div:nth-child(2) {
background-color: green;
}
div:nth-child(3) {
background-color: yellow;
}
您必须对元素进行适当的定位,例如:
div:nth-child(2) { background-color: green; }
使用div:nth-of-type(n)代替nth-child。 这样,您可以确保仅将div作为目标。
这是因为您没有为特定元素指定nth-child,而是将其应用于任何元素选择器。 这就是为什么:nth-child(2)
也是主体元素的原因,因为它是根元素html
的第二个元素。
您可以覆盖应用于:nth-child(2)
的正文的css规则:
/*just add :root in your existing body to make it greater specificity*/
:root body{
background-color: transparent;
}
:nth-child(2){
background-color: green;/*this will not override to body bgcolor*/
}
但是我建议您对特定元素使用:nth-child
,它比上述方法更好,因为在上述方法中:root body
比以前具有更大的特异性,并且会给简单元素css规则覆盖带来一些问题。
div:nth-child(2){
background-color: green;
}
您的选择器:nth-child(x)
可以读为*:nth-child(x)
表示每个x
子代。
您可以将其设置为body :nth-child(x)
以将其范围限制为body
任何直接x
子对象,也可以将其设置为div:nth-child(x)
以将其范围限制为作为其父级的x
子对象的任何div
body { font-size: 50px; text-align: center; } div { width: 30px; height: 30px; background-color: red; } div:nth-child(1) { background-color: blue; } div:nth-child(2) { background-color: green; } div:nth-child(3) { background-color: yellow; }
<div></div> <div></div> <div></div> <div></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.