Easy Zebra Lists and Tables with CSS & Jquery

Start off with a simple list like the one below:

<ul> <li>content goes here</li> <li>content goes here</li> <li>content goes here</li> <li>content goes here</li> </ul>

add something like this to your style sheet:

li.stripe{ background-color: lightpink; }

now we add a class to our ul so our list code looks like this :

<ul class="zebra"> <li>content goes here</li> <li>content goes here</li> <li>content goes here</li> <li>content goes here</li> </ul>

time to add the jquery magic in our head:

<script src="/jquery.js"></script> <script type="text/javascript"> $(function(){ $('.zebra li').addClass('stripe'); }); </script>

Now our simple list with look like this because jquery will dynamically add the class .stripe to each li item of our ul:

Now obviously that's not what we wanted. We want the li items to ALTERNATE colors. Just a small additional piece of jquery does the trick. All we're going to do is add either :even or :odd to the end of our li element in our original query script

<script src="/jquery.js"></script> <script type="text/javascript"> $(function(){ $('.zebra li:even').addClass('stripe'); }); </script> Now we get the desired results!

Feel like taking it a step further? Why not add a hover class or a different alternating color besides the default white?

The Code:

<style type="text/css"> li.stripe-even{ background-color: lightpink; height:20px; list-style-type:none; } li.stripe-odd{ background-color: lightblue; height:20px; list-style-type:none; } ul.zebra li:hover{ background-color: yellow; } </style> <script src="/jquery.js"></script> <script type="text/javascript"> $(function(){ $('.zebra li:even').addClass('stripe-even'); $('.zebra li:odd').addClass('stripe-odd'); )}; </script>

Easy Cheesy huh!?

*Note - adding :hover to your li items in your style sheet should work if you're using a modern browser. Doesn't work in ie6 but you can add a hover event with jquery too if you need to. : ) Or just get with the times and use a modern browser : D

Now the cool part about this is that it can work with tables and definition lists too!

So there you have it! With a single line of jquery and some css styling you can quickly and dynamically add zebra stripes to your site's lists or tables!

download the required jquery file here. Make sure to either rename it to jquery.js or call to the correct file name in your script src. Make sure you're also calling to it correctly according to your file structure / directory setup. For example, I simply used src="/jquery.js" because my file was named jquery.js and it was placed in the root directory of my web site along with this .html file.