You must have seen HTML lists with alternating colors for the items it contains. This is to say that the even numbered list items will have one CSS style and the odd numbered items will have another CSS style.
HTML elements (tags) OL, UL and LI are used to create lists on web pages. These tags are quite handy and easy to use. They also come with several options to adjust look and functionality of the created lists.
Concerning such lists, one functionality is, however, still not available in HTML or CSS standards. At times, in these lists, we want to distinguish even and odd items for better scannability and readability. Such distinction could be achieved by different background colors, different font-style, font-size, text color etc. You can bring visual distinction among even odd list items by using one of the following methods.
If you are using jQuery, making alternate items look different is very easy. Moreover, jQuery automatically manages alternate styles even if you add or delete list items. Therefore, it is preferred method, especially for dynamic lists. Here is the jQuery code, that will do the trick:
<script> $(document).ready(function(){ $('#ID-OF-DIV ul li:nth-child(odd)').addClass('alternate'); }); </script>
ID-OF-DIV is the id of the DIV element in which list has been placed.
The above code walks through all the list items and adds a CSS class called “alternate” to every list item that comes at odd position. You can name this CSS class whatever you wish to (just change the name in code accordingly)
Here is sample alternate class. This defines background color to be #efefef.
.alternate{ background:#efefef; }
Effectively, all the odd items in your list will have #efefef background color. You can define other style rules like font-size, font-family, font-weight etc. in this CSS class as per your need.
If you are not using or don’t want to use jQuery, you’ll have to manually give different class to all odd (or even) list items. If you will add or delete any list item -you’ll have to manually reassign class. Here is how you can do it:
<ul> <li>Item 1</li> <li class="alternate">Item 2</li> <li>Item 3</li> <li class="alternate">Item 4</li> <li>Item 5</li> </ul>
As you can see, its not a very nice way to accomplish our goal. So, we recommend that you use jQuery and make your life easier! Indeed the motto of jQuery is “write less, do more”!
CSS simplification:
ul.striped li:nth-child(even) {
background:#efefef;
}
Only need 1 class
Item1
Item2
Item3
Item4
Item5
I was searching for a simple solution to place two tables side by side. However using DIV to place 2 contents side by side using styles seemed the simpler and it is working for me. Thank you.