2017-03-08 62 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>