View Full Version : Alternate background colors for list items

12-11-2010, 07:53 PM
For example, question has been posed elsewhere on the web:


I know I can manually assign classes or ids, but that's not satisfactory because the list will be dynamic and changing and i don't want to have to go thru and manually change the classes everytime a new item is inserted in which disrupts the alternating pattern. moreover it's a very long list...

As for JQuery, another suggestion in the forum in the link, I'm still a html css learner, with no JavaScript knowledge, so unless you can give me a crash course in JavaScript better scrap that idea.

Bottom line, I want or more efficient, or automated solution to alternating background colors for list items.

If you're wondering it's for the vertical menus on my site: http://www.mathannotated.com/ so that alternating links can be easily discerned from ea. other.

12-12-2010, 02:32 AM
I would make the links as a list, and then add classes to each <li> tag. TO make them alternate colours.

<ul id="menu">
<li class="shaded">Link</li>
<li class="shaded">Link3</li> and so on and then in the CSS
.shaded {
background: #eee;

Really this is the only way that I know using css and html, you have to manually add the link so it is no big deal to add a class if you need to, if you want something dynamic then you would need to look for a script, but I have not seen a script for this. Found this dont know if it helps http://scripts.top4download.com/alternate-table-row-list-item/ozjfo.html

12-12-2010, 03:35 AM
Hello ptrcao,
A class would be how you would normally do it.

When you don't have control over the alternating classes on your li, you still want control over your colors via CSS.

Try this:
Make the CSS that styles your li's, as if you had a list with one color on the li and one color on the li.alternate.

Once that CSS is in place it's easy then to have a jQuery that adds the .alternate to every other li.
Try using this snippet -
$('#myList li:nth-child(odd)').addClass('alternate');

And, just for fun, this works in FF3.x -
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
html, body {
margin: 0;
background: #FC6;
#container {
width: 800px;
margin: 30px auto;
background: #999;
overflow: auto;
li { background: green; }
li:nth-child(odd) { background: red; }
<div id="container">
<ul id="nav">
<li><a href="link">linky</a></li>
<li><a href="link">linky</a></li>
<li><a href="link">linky</a></li>
<li><a href="link">linky</a></li>
<li><a href="link">linky</a></li>
<!--end container--></div>