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:

<table>
    <thead>
	<tr>
	    <td>Sno</td>
	    <td>First Name</td>
	    <td>Last Name</td>
	    <td>Age</td>
	    <td>Gender</td>
	</tr>
    </thead>

    <tbody>
	<c:forEach var="person" items="${persons}" varStatus="i">
	    <c:choose>
		<c:when test="${(i.count) % 2 == 0}">
		    <tr class="even">
		</c:when>
		<c:otherwise>
		    <tr class="odd">
		    </c:otherwise>
		</c:choose>
		<td>${i.count}</td>
		<td>${person.firstName}</td>
		<td>${person.lastName}</td>
		<td>${person.age}</td>
		<td>${person.gender}</td>
	    </tr>
	</c:forEach>
    </tbody>
</table>

 
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;
    }
</style>
About these ads

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

    jostein

    October 14, 2010 at 01:55

  3. Gal

    March 10, 2011 at 02:54

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

    Goutham

    May 26, 2011 at 17:58

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

    mike

    September 29, 2011 at 20:55

  6. thanks it helped a lot in working with jstl

    bu1

    January 2, 2012 at 15:23


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: