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?

Jeff
  • 1,405
  • 3
  • 26
  • 46

6 Answers6

13

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

ajcw
  • 23,604
  • 6
  • 30
  • 47
  • 3
    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 Oct 22 '10 at 11:07
4

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

Sam Dufel
  • 17,560
  • 3
  • 48
  • 51
3

Try this using JQuery:

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

See it in action here

bla
  • 5,350
  • 3
  • 25
  • 26
3

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,518
  • 2
  • 18
  • 26
2

You can also try without CSS, its simple.

Code:

    **var rowCount = document.getElementById("tableID").rows.length;
    var row = table.insertRow(rowCount);
        var cell1 = row.insertCell(0);
        cell1.style.backgroundColor = "yellow";
                    cell1.innerHTML = "hey";
                    var cell2 = row.insertCell(1);
        cell2.style.backgroundColor = "green";
                    cell2.innerHTML = "hello";**

Here its creating dynamically row for the table and filling different color to coloumns.

hope this help..!! Thanks

Abhishek
  • 1,558
  • 16
  • 28
2

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
  • 511
  • 2
  • 3