What is the easiest way to alternate row colors in an HTML table (a.ka. striping). Most of my tables are created in XSL templates like the following, with the table, thead, etc.. defined in another template.
<xsl:template match="typ:info">
<tr>
<td>
<xsl:value-of select="typ:dateAccessed" />
</td>
<td>
<xsl:value-of select="typ:loginId" />
</td>
</tr>
</xsl:template>
My preference is to use alternating classes on the elements.
If you must produce hard-coded colors in HTML:
<xsl:template match="typ:info">
<xsl:variable name="css-class">
<xsl:choose>
<xsl:when test="position() mod 2 = 0">even</xsl:when>
<xsl:otherwise>odd</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<tr class="{$css-class}">
<td>
<xsl:value-of select="typ:dateAccessed" />
</td>
<td>
<xsl:value-of select="typ:loginId" />
</td>
</tr>
</xsl:template>
With today's browsers you are much better off using CSS and tr:nth-child(odd)
.
This results in less hassle on the XSLT side, much cleaner HTML markup - and it's compatible with client-side table sorting and -filtering.
You could also use css3.
tr:nth-child(odd) { background: #ff0000; }
Supported as of IE9 an for quite some time by all the other browsers.
Use an XSL:When and compare position mod 2 to get odd or even rows to alter classes when needed like:
<xsl:choose>
<xsl:when test="position() mod 2 = 1">
<td class="odds">blah</td>
</xsl:when>
<xsl:otherwise>
<td class="even">blah</td>
</xsl:otherwise>
</xsl:choose>
EDIT: Getting my odd/even the right way around sigh
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With