简体   繁体   中英

How to alternate colors in two columns in css3 selector?

If I have this code

 #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> 

This displays like

A B
C D
E F 
G H 
I J

Which is good, however, I want the background colors to be like

red blue
blue red
red blue
blue red
red blue

However the above code makes each column the same color. Is there a pure-css3 way I can do this?

 #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> 

Check this out:

 #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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM