tags:

views:

107

answers:

5

i am using a table with alternate row color with this.

css

tr.d0 td {
    background-color: #CC9999; color: black;
}
tr.d1 td {
    background-color: #9999CC; color: black;
}

html

<table>
<tr class="d0"><td>One</td><td>one</td></tr>
<tr class="d1"><td>Two</td><td>two</td></tr>
</table>

here i am using class for tr but i want to use only for table. when i use class for table than this apply on tr alternative.

can i write my html like this with use css ?

<table class="alternate_color">
    <tr><td>One</td><td>one</td></tr>
    <tr><td>Two</td><td>two</td></tr>
    </table>

is there a way to make like this?

A: 

You have the :nth-child() pseudo-class:

table tr:nth-child(odd) td{
}
table tr:nth-child(even) td{
}

Be aware, though, that its browser support is pretty poor. That's why setting class="odd" is such a common technique.

Álvaro G. Vicario
A: 

You can use nth-child(odd/even) selectors however not all browsers (ie 6-8, ff v3.0) support these rules hence why most solutions fall back to some form of javascript/jquery solution to add the classes to the rows for these non compliant browsers to get the tiger stripe effect.

redsquare
+8  A: 

There is a CSS selector, really a pseudo-selector, called nth-child. In pure CSS you can do the following:

tr:nth-child(even) {
    background-color: #000000;
}

Note: No support in IE, even IE 8.

Or, if you have jQuery:

$(document).ready(function()
{
  $("tr:even").css("background-color", "#000000");
});
Russell Dias
A: 
<script type="text/javascript">
$(function(){
  $("table.alternate_color tr:even").addClass("d0");
   $("table.alternate_color tr:odd").addClass("d1");
});
</script>
Pranay Rana
OK I know jQuery is fairly ubiquitous on this site but regardless you shouldn't post jQuery without explanation. This script won't work on its own.
DisgruntledGoat
A: 

can i write my html like this with use css ?

Yes you can but then you will have to use the :nth-child() pseudo selector (which has limited support though):

table.alternate_color tr:nth-child(odd) td{
   /* styles here */
}
table.alternate_color tr:nth-child(even) td{
   /* styles here */
}
Sarfraz
one bg color is working but 2nd bg color is not.
kc rajput