Is there an easy way to style alternating rows in the <tbody> area of my HTML Table?
Thanks,
Debbie
Is there an easy way to style alternating rows in the <tbody> area of my HTML Table?
Thanks,
Debbie
With CSS3 there is but if your panning on supporting IE then you will also need a JavaScript fallback which can easily be found via Google, see the below example for the CSS version.
td:nth-child(2n+2) {
background-color: red;
}
Is that CSS2 or CSS3?
I thought there was a CSS 2 solution?
Debbie
It’s CSS3, as far as i am aware no CSS2 solution exists because there are no pseudo selectors that can alternate between elements.
The only CSS2 “solution” is to put a class (like say class=“even”) on every other row and target them that way. (some people will put alternating classes on every row – we call these people … well, I’ll be nice and not say it.)
Which usually isn’t a big deal if you’re building that table in something like PHP or ASP. set a counter and modulo it by two.
As of the 29[sup]th[/sup] of Sept., the Selectors level 3 module is the current recommendation. The :nth-child() pseudo class is supported by the four current major rendering engines, including IE9+.
cheers,
gary
Of limited use and inefficient (code wise) but you could style alternate rows for IE7+ using the adjacent selector.
e.g.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<style type="text/css">
table {
border-collapse:collapse;
width:80%;
margin:auto
}
thead tr th{background:#fcf}
tbody tr td { background:red }
tbody tr+tr td { background:yellow }
tbody tr+tr+tr td { background:red }
tbody tr+tr+tr+tr td { background:yellow }
tbody tr+tr+tr+tr+tr td { background:red }
tbody tr+tr+tr+tr+tr+tr td { background:yellow }
tbody tr+tr+tr+tr+tr+tr+tr td { background:red }
tbody tr+tr+tr+tr+tr+tr+tr+tr td { background:yellow }
</style>
</head>
<body>
<table>
<thead>
<tr>
<th scope="col">head</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
<tr>
<td>5</td>
</tr>
<tr>
<td>6</td>
</tr>
<tr>
<td>7</td>
</tr>
<tr>
<td>8</td>
</tr>
</tbody>
</table>
</body>
</html>
Obviously no use for dynamic data but for a small fixed row table may be useful.
Double Dee, look up IE7-js on Google. It’s a javascript code that makes CSS 3 usable on versions 6 through 9. Then you can use “nth-of-type(odd)” or even. Just be aware that for some reason IE 7 will interpret the first row opposite to how it should, so you just use a conditional comment to switch odd to even.
I’ve done this on a project where I have to update the table by hand. It’s made maintenance a snap.