tags:

views:

78

answers:

5

In HTML, I am adding rows dynamically in a table I need to give different colors for alternative rows using CSS How can I acheive this?

+3  A: 

Just create 2 css classes, and assign them to the tags alternately.

Sam Dufel
+7  A: 

To achieve this effect (known as zebra striping) in all browsers using just CSS you'll need to add a class to each row (e.g. odd and even) and give them different colours.

If you want to achieve this with just CSS and are not concerned with supporting older browsers (IE6-8) you should use the CSS3 nth-child pseudo element. This can achieve the required effect without the extra class mark-up, e.g.

tr:nth-child(odd) {
  background-color: #FF0;
}

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

However if you want full browser support and don't mind using javascript there are a number of scripts available, both jQuery plugins and plain old javascript. Maybe try this for starters?

http://docs.jquery.com/Tutorials:Zebra_Striping_Made_Easy

John Catterfeld
Consider providing the information which browsers support this CSS property: Firefox 3.5+, Internet Explorer 9 beta, Opera 9.5+, Chrome and Safari. So, the only relevant older browsers which do not support it are IE6-8
Šime Vidas
+2  A: 

Try this using JQuery:

$('tr:even').css('background-color', 'grey');

See it in action here

Lee Sy En
+2  A: 

What are you using to create the table, if it is rails you can use?:

= cycle('odd', 'even')

or you can do it in PHP like this:

$i = 0;

=($i++%2==1) ? 'odd' : 'even'

DJ Forth
+1  A: 

just create the css classes for rows(odd and even) but dont forget that the font color for text should be readeable regarding the background color

.row_odd{
    background: #ffffff;
    color: #000;
}
.row_even{
        background: #faf8f5;
        color: #000;
}

Then in the xhtml you have to set the class for each row. For example, using php while you are iterating on rows you can set the value of the variable $class.

<tr class="<?=$class?>" onmouseover=""> 
   <td class="center col_check">...</td>
   <td class="links">...</td>  
   <td class="center">...</td>
</tr>

In addition, you can make other css classes for each column depends of what you want!!

Nervo Verdezoto