html - without - table alternate row color combinations

How to alternate HTML table row colors using JSP? (4)

(this answer only pertains to the CSS side of things...)

As a matter of course, I always target the child TD's like so:

tr.odd td {}
tr.even td {}

The reason being is that IE actually applies TR background-color by removing the value set on the TR and applying it to each individual TD within that TR. Sometimes you might have a css reset or other css rules that overrides IE's strange way of doing TR background-color, so this is a way to make sure you avoid that.

Also, you might want to consider setting just

tr td {background-color: #EEDDEE}


tr.odd td {background-color: #EEEEDD}

so your code is slightly less verbose

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">
    <td><c:out value="${element.field}"/></td>

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">

I don't use JSP, so I can't give you an answer in your language, but here's what I do (using pseudo code)

counter = 0
foreach (elements)
    counter = counter + 1
    output: <tr class="row{counter % 2}">...</tr>

Personally, I name the classes "row0" and "row1", which lets you alternate between them with a simple modulus calculation, also, if you decide to have rows alternating in triples or quads (instead of pairs), you can easily extend it to row2, row3 and change your output code to be counter % 4, etc.

Just do like this and is going to work:

table tr:nth-child(odd) { background-color: #ccc; }