Select doubles using nth-child() in CSS3

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!