I am using a table with alternate row color with this.
tr.d0 td {
background-color: #CC9999;
color: black;
}
tr.d1 td {
background-color: #9999CC;
color: black;
}
<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 using CSS?
<table class="alternate_color">
<tr><td>One</td><td>one</td></tr>
<tr><td>Two</td><td>two</td></tr>
</table>
How can I make the rows have "zebra stripes" using CSS?
There is a CSS selector, really a pseudo-selector, called nth-child. In pure CSS you can do the following:
Note: No support in IE 8.
Or, if you have jQuery:
There is a fairly easy way to do this in PHP, if I understand your query, I assume that you code in PHP and you are using CSS and javascript to enhance the output.
The dynamic output from the database will carry a for loop to iterate through results which are then loaded into the table. Just add a function call to the like this:
then add the function to the page or library file:
}
Now this will alternate dynamically between colors at each newly generated table row.
It's a lot easier than messing about with CSS that doesn't work on all browsers.
Hope this helps.
You have the :nth-child() pseudo-class:
In the early days of
:nth-child()
its browser support was kind of poor. That's why settingclass="odd"
became such a common technique. In late 2013 I'm glad to say that IE6 and IE7 are finally dead (or sick enough to stop caring) but IE8 is still around—thankfully, it's the only exception.