tags:

views:

325

answers:

4

Is it possible to style alternate table rows without defining classes on alternate <tr> tags?

With the following table, can CSS define alternate row styles WITHOUT having to give the alternate rows the class "row1/row2"? row1 can be default, so row2 is the issue.

<style>
.altTable td { }
.altTable .row2 td { background-color: #EEE; }
</style>

<table class="altTable">
 <thead><tr><td></td></tr></thead>
 <tbody>
  <tr><td></td></tr>
  <tr class="row2"><td></td></tr>
  <tr><td></td></tr>
  <tr class="row2"><td></td></tr>
 </tbody>
</table>
A: 

Give a class of row2 on tbody and then style your alternate rows with class row1. Other rows will inherit the class row2 from the tbody.

<style>
.row1 { color: red }
.row2 { color: blue }
</style>

<table class="altTable">
 <thead><tr><td></td></tr></thead>
 <tbody class="row2">
  <tr class="row1"><td>row 1</td></tr>
  <tr><td>row 2</td></tr>
  <tr class="row1"><td>row 1</td></tr>
  <tr><td>row 2</td></tr>
 </tbody>
</table>
rahul
+2  A: 

Yes! You can do it with pure CSS and no classes on browsers that support the "+" selector of CSS:

.altTable tr td,
.altTable tr+tr+tr td,
.altTable tr+tr+tr+tr+tr td { background-color: #EEE; }

.altTable tr+tr td,
.altTable tr+tr+tr+tr td,
.altTable tr+tr+tr+tr+tr+tr td{ background-color: #fff; }

Probably not the best approach, but doable.

If you don't mind a little Javascript, jQuery gives it to you much concisely:

$('.altTable tr:odd').addClass('odd');
ndp
yeah the styles work perfectly... but nasty for 50+ rows! I think the jquery will work well for now.
Peter
yes the jquery works with $(document).ready(function(){ my rows also have a :hover that's now broken - what would be the jquery for this, something like $('.altTable tr:odd:hover').addClass('odd:hover');
Peter
+2  A: 
tr:nth-child(even) { background: #FFF; }
tr:nth-child(odd) { background: #EEE; }

Does not work in IE, but it's a purely presentational thing, the content will work fine anyway, so I don't think it's a huge issue -- depending on the % of regular IE users on your site.

Jacob R
I guess this could be the solution, I didn't state CSS2 so when CSS3 is fully supported it's good to see additional options like this.
Peter
A: 

@ndp - Great job, works. made my day

bion