可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Say I have the following structure for a list:
<ul> <li></li><li></li> <li></li><li></li> </ul>
and each <li>
is 50% width so I want every two to have the same background colour like this:
<ul> <li style="background:#CCC;"></li><li style="background:#CCC;"></li> <li style="background:#DDD;"></li><li style="background:#DDD;"></li> <li style="background:#CCC;"></li><li style="background:#CCC;"></li> <li style="background:#DDD;"></li><li style="background:#DDD;"></li> </ul>
Can I do this using the 'nth-child()' CSS selector so as to minimise code?
回答1:
ul li:nth-child(4n+1), ul li:nth-child(4n+2) { background: #CCC; } ul li:nth-child(4n+3), ul li:nth-child(4n+4) { background: #DDD; }
This will give you every 4th element starting with the 1st, and 2nd as color #CCC and every 4th element starting with the 3rd and 4th as #DDD
jsfiddle here: http://jsfiddle.net/mU2tn/1/
回答2:
li{ /* All LIs*/ } li:nth-child(4n+1), li:nth-child(4n+2) { /* Li 1, 2, 5, 6, 9, 10 */ }
回答3:
Yes you can do it with only CSS(3). Here's a jsFiddle example.
li { width:100%; } li:nth-child(4n) { background:#999; } li:nth-child(4n-1) { background:#999; } li:nth-child(4n-2) { background:#ccc; } li:nth-child(4n-3) { background:#ccc; }
回答4:
I believe this CSS should get what you aim to do.
ul li:nth-child(4n+1), ul li:nth-child(4n+2) { background: #ccc; } ul li:nth-child(4n+3), ul li:nth-child(4n){ background: #ddd; }
This JSFiddle shows it in action. http://jsfiddle.net/u2W84/
回答5:
Perhaps all the other answers work, but this is what I'd do:
ul li { background: red; } ul li:nth-child(odd), ul li:nth-child(odd) + li { background: green; }
Edit: no sorry, that didn't work :P Gimme a sec.