Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alternate HTML table row colors using JSP?

Tags:

html

css

jsp

jstl

How do I alternate HTML table row colors using JSP?

My CSS looks something like:

tr.odd {background-color: #EEDDEE} tr.even {background-color: #EEEEDD} 

I want to use <c:forEach> to iterate over a collection.

<c:forEach items="${element}" var="myCollection">   <tr>     <td><c:out value="${element.field}"/></td>     ...   </tr> </c:forEach> 

I need an int count variable or boolean odd/even variable to track the row. Then my <tr> tag would look something like:

<tr class="odd or even depending on the row"> 
like image 672
Steve Kuo Avatar asked Oct 28 '08 00:10

Steve Kuo


People also ask

How do you change the color of a table in HTML?

What to Know. Easiest: add the style property background-color to the table, row, or cell tag. Next easiest: use the attribute bgcolor.


2 Answers

Use the varStatus attribute on your forEach tag and JSTL will manage an instance of a javax.servlet.jsp.jstl.core.LoopTagStatus for you in the variable name you specify.

You can then use a ternary operator to easily output the appropriate class name:

<c:forEach items="${element}" var="myCollection" varStatus="loopStatus">   <tr class="${loopStatus.index % 2 == 0 ? 'even' : 'odd'}">     ...   </tr> </c:forEach> 

This JSTL primer from IBM has more information about the core tag library and what it gives you.

like image 130
Jonny Buchanan Avatar answered Oct 08 '22 14:10

Jonny Buchanan


Just do like this and is going to work:

table tr:nth-child(odd) { background-color: #ccc; } 
like image 43
Cifi Avatar answered Oct 08 '22 14:10

Cifi