簡體   English   中英

使用nth-child將CSS樣式應用於特定標簽,甚至它們之間也存在其他標簽

[英]Apply CSS styles to specific tag using nth-child even exists other tags between them

我對CSS3的專家有一個關於nth-child選擇器的簡單問題(這里我是n00b)

我有以下簡單的html代碼:

<div>1</div>
<div>2</div>
<div>3</div>
<span>span3</span>
<div>4</div>
<div>5</div>

CSS樣式:

div:nth-child(2n+1) {
    color: red;
}

div, span {
    float: left;
}

我為您創建了一個小提琴: http : //jsfiddle.net/Q8aPe/

結果是:

123span345 ,其中1,3,4和5的顏色為紅色。

我期望的是: 1,3,5為紅色。

為什么呢 nth-child不在乎標記child嗎? 還是只引用一個元素(與什么標簽無關)?

謝謝

沒錯, nth-child根據元素在其所有同級元素中的位置來決定。 您想要的是nth-of-type ,它基於元素在所有潛在的CSS匹配中的位置。

http://jsfiddle.net/Q8aPe/1/

div:nth-of-type(2n+1) {
    color: red;
}

嘗試使用:nth-of-type()而不是:nth-child()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM