Conditional alternative table row styles

Is it possible to create alternate table rows without defining classes in alternate tags <tr>

?

In the following table, CSS can define alternate row styles without having to give alternate rows to the "row1 / row2" class? row1 might be the default, so row2 is the problem.

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

      

+2


source to share


3 answers


tr:nth-child(even) { background: #FFF; }
tr:nth-child(odd) { background: #EEE; }

      



Doesn't work in IE, but this is purely presentation thing, the content will still work fine, so I don't think this is a huge issue - depending on the% of regular IE users on your site.

+7


source


Yes! You can do this with pure CSS and no classes in browsers that support the "+" CSS selector:

.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; }

      

This is probably not the best approach, but doable.



If you don't mind a little Javascript, jQuery gives you this very succinctly:

$('.altTable tr:odd').addClass('odd');

      

+2


source


Give class row2 to tbody and then create alternate rows with class row1. Other rows inherit the row2 class from 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>

      

0


source







All Articles