开发者

Alternating background color in HTML UL

开发者 https://www.devze.com 2023-02-13 02:29 出处:网络
I\'d like to alternate the background color in a HTML开发者_高级运维 un-ordered list without using JQuery.Best option would be CSS3 :nth-child selector:

I'd like to alternate the background color in a HTML开发者_高级运维 un-ordered list without using JQuery.


Best option would be CSS3 :nth-child selector:

#myul li:nth-child(odd) {
    background-color: red;
}
#myul li:nth-child(even) {
    background-color: green;
}

or if for some reason you really need javascript solution:

<style>
    li.even { background-color: red; }
    li.odd { background-color: blue; }
</style>

var ul = document.getElementById('myul');
var items = ul.getElementsByTagName('li');
for (var i = 0; i < items.length; i++) {
    var class = i % 2 == 0 ? 'even' : 'odd';
    items[i].className = class;
}

or as already mentioned you could just generate the classes server-side.


<style>
.uneven{background-color:red;}
.even{background-color:green;}
</style>
<ul>
<li class="uneven">A</li>
<li class="even">B</li>
<li class="uneven">C</li>
<li class="even">D</li>
</ul>

Missing the point probably..


You can do it with just CSS: http://www.w3.org/TR/css3-selectors/#nth-child-pseudo

This won't work in IE, though.


Here's how you can do it on all UL's in the page without any CSS - http://jsfiddle.net/2G7wx/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消