tim
tim

Reputation: 49

How to alternate table row background colors with JSTL?

How do i alternate table rows with 2 seperate colours but i nid the header row to be of another colour. Is it possible? i am required to use the looping technique. oh no i aint allowed to post pictures. but it looks something like a table with 5 rows and the header row is blue in colour while the other 4 rows are red>white>red>white

Upvotes: 5

Views: 8461

Answers (1)

BalusC
BalusC

Reputation: 1108712

Use <c:forEach> with a varStatus and some lines of CSS.

<table>
    <thead>
        <tr>
            <th>header1</th>
            <th>header2</th>
            <th>header3</th>
        </tr>
    </thead>
    <tbody>
        <c:forEach items="${bean.list}" var="item" varStatus="loop">
            <tr class="${loop.index % 2 == 0 ? 'even' : 'odd'}">
                <td>${item.property1}</td>
                <td>${item.property2}</td>
                <td>${item.property3}</td>
            </tr>
        </c:forEach>
    <tbody>
</table>

with CSS

tr.even { background: red; }
tr.odd { background: white; }

In the above example, the header is just separated from the body. When the table row index in the body is a multiple of 2 (even), then it get class="even", otherwise class="odd" (open page in browser, rightclick it and View Source to see it yourself). With CSS you can just control the style of the invididual elements. To give the header row a blue background, just add

thead tr { background: blue; }

Upvotes: 11

Related Questions