Geek Lair

Zebra striping tables with JSTL and CSS

with 6 comments

Zebra striping is giving adjacent rows in a table different colors and alternate rows the same color:

Zebra Striped Table

Zebra Striped Table

One way to do it is using JavaScript and CSS. There are a lot of articles describing how to do so. This method has one disadvantage – if the user disables JavaScript in the browser, the table will not be striped. The only way is to hard code the style for each row. This is easily done using JSTL.

If we have a list of objects of type Person, then we can iterate over them using the JSTL <c:forEach> action and render a row for each item. Even and odd rows can be determined from the loop counter:

	    <td>First Name</td>
	    <td>Last Name</td>

	<c:forEach var="person" items="${persons}" varStatus="i">
		<c:when test="${(i.count) % 2 == 0}">
		    <tr class="even">
		    <tr class="odd">

Even rows will have the style “even” and odd rows “odd”. Here are the CSS styles I used:

<style type="text/css">
    table {
	border-collapse: collapse;
	text-align: center;
    td {
	border: 1px solid #000;
    thead {
	background-color: #000;
	color: #fff;
	font-weight: bold;
    thead td {
	padding: 0 .5em;
    .odd {
	background-color: #E6E6E6;
    .even {
	background-color: #fff;

Written by anonir

December 16, 2008 at 20:07

Posted in JEE, Web

Tagged with ,

6 Responses

Subscribe to comments with RSS.

  1. This helped me on a project that I’m currently working on. Thanks!

    Robert Fauver

    June 25, 2010 at 23:32

  2. Thanks a lot for this


    October 14, 2010 at 01:55

  3. Gal

    March 10, 2011 at 02:54

  4. Whats count here ?? i.e,. i.count


    May 26, 2011 at 17:58

  5. Thanks due good one I just used it , it worked in the first go , cool :).


    September 29, 2011 at 20:55

  6. thanks it helped a lot in working with jstl


    January 2, 2012 at 15:23

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: