Zebra striping tables with JSTL and CSS
Zebra striping is giving adjacent rows in a table different colors and alternate rows the same color:
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>
Advertisements
This helped me on a project that I’m currently working on. Thanks!
Robert Fauver
June 25, 2010 at 23:32
Thanks a lot for this
jostein
October 14, 2010 at 01:55
Thanks for the info, however a cooler way exist:
http://stackoverflow.com/questions/241897/how-to-alternate-html-table-row-colors-using-jsp
Gal
March 10, 2011 at 02:54
Whats count here ?? i.e,. i.count
Goutham
May 26, 2011 at 17:58
Thanks due good one I just used it , it worked in the first go , cool :).
mike
September 29, 2011 at 20:55
thanks it helped a lot in working with jstl
bu1
January 2, 2012 at 15:23