2017-04-20 19 views
9

重複第n個孩子,我想樣式項1至10,但不是做沒有在CSS

&.nth-child(1) { //style } 
&.nth-child(2) { //style } 
&.nth-child(3) { //style } 

等..

在CSS任何範圍內選擇?

+0

我認爲你正在尋找 「循環」 通過CSS?你可以用'sass'或者使用另一個'css'預處理器來做到這一點...... – wahwahwah

回答

10

您可以an+b格式使用:nth-child方程(其中一個整數代替abn0, 1, 2,....)。

li:nth-child(-n+10) { 
 
    color: red 
 
}
<ol> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
</ol>


UPDATE:如果你需要一個範圍內的元素,然後使用多個:nth-child選擇。

li:nth-child(n+5):nth-child(-n+10) { 
 
    color: red 
 
}
<ol> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
    <li>a</li> 
 
</ol>

1

以下代碼段CSS分配範圍爲2〜3。它調整到您的要求。

說明:

nth-child(n+2)開始從第二要素選擇爲正向。 nth-child(-n+3)開始從第3個元素向後選擇。

結合範圍內的兩個結果。

li:nth-child(n+2):nth-child(-n+3){ 
 
background: #000; 
 
color: #fff 
 
}
<li>1</li> 
 
<li>1</li> 
 
<li>1</li> 
 
<li>1</li> 
 
<li>1</li> 
 
<li>1</li>