2017-02-11 29 views
4

我想了解爲什麼nth-of-type選擇器沒有按預期工作。我的目標是在第一個藍色之後將第一個.row元素設爲紅色,並將所有其他元素設爲紅色,同時使項目保持綠色。試圖瞭解nth類型的css選擇器

https://jsfiddle.net/darrengates/pa34zyjd/14/

.wrapper div { 
 
    width: 200px; 
 
    background-color: green; 
 
    color: white; 
 
    margin: 5px; 
 
    padding: 5px; 
 
} 
 
.wrapper .row:nth-of-type(n+1) { 
 
    background-color: red; 
 
} 
 
.wrapper .row:nth-of-type(n+2) { 
 
    background-color: blue; 
 
}
<div class="wrapper"> 
 
    <div class="option">option</div> 
 
    <div class="button">some button</div> 
 
    <div class="row">I wanna be red</div> 
 
    <div class="row">I wanna be blue</div> 
 
    <div class="row">I wanna be blue</div> 
 
    <!-- all other row elements after the first should be blue --> 
 
</div>

+0

[這](http://stackoverflow.com/a/9313956/7094618)可以幫助你理解。 – Faegy

+0

最清楚最好的描述我還沒有找到這裏:https://css-tricks.com/almanac/selectors/n/nth-of-type/ – Sam0

+0

可能有[第n類型與第n類型孩子] (http://stackoverflow.com/questions/9313769/nth-of-type-vs-nth-child); *這[回答](http://stackoverflow.com/a/9313845/6381711)你的問題和[這](http://stackoverflow.com/a/42170738/6381711)回答[Pangloss](https:/ /stackoverflow.com/users/483779/pangloss)可能是基於您的方案的最佳方法。* – nyedidikeke

回答

3

n-th-of-type選擇指標籤類型在同一水平上,類,在這種情況下,div標籤,其是內部.wrapper兄弟姐妹。因此,你需要這個CSS,因爲它們是第三和第四div在那裏:

.wrapper .row:nth-of-type(n+3) { 
    background-color: red; 
} 
.wrapper .row:nth-of-type(n+4) { 
    background-color: blue; 
} 

https://jsfiddle.net/cb3qd8t6/

2

nth-*選擇只認準元素不是類名的類型。在你的榜樣,我會用~+做到這一點:

.wrapper div { 
 
    width: 200px; 
 
    background-color: green; 
 
    color: white; 
 
    margin: 5px; 
 
    padding: 5px; 
 
} 
 
.wrapper .row { 
 
    background-color: red; 
 
} 
 
.wrapper .row ~ .row { 
 
    background-color: blue; 
 
}
<div class="wrapper"> 
 
    <div class="option">option</div> 
 
    <div class="button">some button</div> 
 
    <div class="row">I wanna be red</div> 
 
    <div class="row">I wanna be blue</div> 
 
    <div class="row">I wanna be blue</div> 
 
    <!-- all other row elements after the first should be blue --> 
 
</div>