2

I am trying to have alternate background colour for each . I understand i can use:

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

As another stack question says, however, that only works if we have same number of <td>s, but in case we have different number of them, we won't have a full coloured row but it will rather stop to the last td.

Is there way I could do it with only css or any jQuery in regards?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
rob.m
  • 9,843
  • 19
  • 73
  • 162

4 Answers4

2

You can assign a class to each row. It should be pretty simple if you are generating your table dynamically.

<style>
    .rowOdd { background: #C0C0C0; }
    .rowEven { background: #CACACA; }
</style>

<table>
    <tr class="rowOdd">
    (...)
    </tr>
    <tr class="rowEven">      
    (...)
    </tr>
 </table>

etc... Or if your layout is really complicated (lots of merged cells) then you can add similar class to each td individually instead of tr.

ZorleQ
  • 1,417
  • 13
  • 23
  • yeah that's quite obvious but if I have less td in a row, that won't work. I guess it's just invalid not to display a all the td unless we use rowspan, which in that case the row will be fine as it be equal width with all the other – rob.m Aug 13 '13 at 08:23
  • Och, that's what you mean. Yes, as far as I know it's bad practice not to have an equal number of td's unless you use rowspans. In most cases table sizing gets screwed up if some rows are different! Afteral, it's a table, just like in excel, and not a free do-what-you-want layout. – ZorleQ Aug 13 '13 at 08:30
1

I would definitely go the CSS3 approach.

This site is really good at explaining all the different nth child syntax that is available

http://nthmaster.com

Chris
  • 805
  • 6
  • 19
1

You can use odd/even numbers to manipulate each row seperately. I think you need a real demo here to understand better.

Live Demo

tr:nth-child(even)
{
    background: red;
}         
tr:nth-child(odd)
{
    background: yellow;
}   
Ali Çarıkçıoğlu
  • 1,304
  • 1
  • 12
  • 21
0

You can use tr:nth-child(2n+1) for odd numbers or tr:nth-child(2n+1) in plain css.

tr:nth-child(2n+1) > td
{
background-color:#F5F5F5
}
chamath
  • 21
  • 1
  • 3