2017-03-08 75 views
4

如果我有這樣的代碼如何在css3選擇器的兩列中交替顏色?

#list>div { 
 
    font-size: 18px; 
 
    float: left; 
 
    margin: 0 10px 10px 0; 
 
    width: 150px; 
 
} 
 

 
#list>div:nth-child(2n+1) { 
 
    clear: left; 
 
} 
 

 
#list>div:nth-child(odd) { 
 
    background-color: red; 
 
} 
 

 
#list>div:nth-child(even) { 
 
    background-color: blue; 
 
}
<div id="list"> 
 
    <div class="list-item">A</div> 
 
    <div class="list-item">B</div> 
 
    <div class="list-item">C</div> 
 
    <div class="list-item">D</div> 
 
    <div class="list-item">E</div> 
 
    <div class="list-item">F</div> 
 
    <div class="list-item">G</div> 
 
    <div class="list-item">H</div> 
 
    <div class="list-item">I</div> 
 
    <div class="list-item">J</div> 
 
</div>

這顯示像

A B 
C D 
E F 
G H 
I J 

這是很好的,但是,我希望背景顏色要像

red blue 
blue red 
red blue 
blue red 
red blue 

但是,上面的代碼使每列的顏色相同。有沒有一種純粹的css3方式可以做到這一點?

回答

6

#list>div { 
 
    font-size: 18px; 
 
    float: left; 
 
    margin: 0 10px 10px 0; 
 
    width: 150px; 
 
} 
 

 
#list>div:nth-child(2n+1) { 
 
    clear: left; 
 
} 
 

 
#list>div:nth-child(4n+1), #list>div:nth-child(4n) { 
 
    background-color: red; 
 
} 
 

 
#list>div:nth-child(4n+2), #list>div:nth-child(4n+3) { 
 
    background-color: blue; 
 
}
<div id="list"> 
 
    <div class="list-item">A</div> 
 
    <div class="list-item">B</div> 
 
    <div class="list-item">C</div> 
 
    <div class="list-item">D</div> 
 
    <div class="list-item">E</div> 
 
    <div class="list-item">F</div> 
 
    <div class="list-item">G</div> 
 
    <div class="list-item">H</div> 
 
    <div class="list-item">I</div> 
 
    <div class="list-item">J</div> 
 
</div>

+0

噢打我吧...和礦用錯顏色 – Miro

+1

您也可以讓所有的列表啓動項目藍色(或紅色)。然後使用一個「nth-child」選擇器組(作爲覆蓋)。這會更簡單。 –

1

檢查了這一點:

#list>div { 
 
    font-size: 18px; 
 
    float: left; 
 
    margin: 0 10px 10px 0; 
 
    width: 150px; 
 
    background-color: red; 
 
} 
 

 

 
#list>div:nth-child(4n+1) { 
 
    background-color: blue; 
 
} 
 

 
#list>div:nth-child(4n) { 
 
    background-color: blue; 
 
} 
 

 
#list>div:nth-child(2n+1) { 
 
clear:left 
 
}
<div id="list"> 
 
    <div class="list-item">A</div> 
 
    <div class="list-item">B</div> 
 
    <div class="list-item">C</div> 
 
    <div class="list-item">D</div> 
 
    <div class="list-item">E</div> 
 
    <div class="list-item">F</div> 
 
    <div class="list-item">G</div> 
 
    <div class="list-item">H</div> 
 
    <div class="list-item">I</div> 
 
    <div class="list-item">J</div> 
 
</div>