[英]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.