1

Somehow I can't figure out the following: Alternate table row color using CSS?

If I use the code suggested in the aforementioned topic the even cells get colored (the first, third and fifth. There is a total of 5 cells in a row). It doesn't matter if I use 'even' or 'odd'.

td:nth-child(odd)
{
    background: #f5f6fa;
}

If use the following code, all the rows get colored.:

tr:nth-child(odd)
  {
        background: #f5f6fa;
  }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
svdh
  • 33
  • 4

1 Answers1

2

@svdh You've got tags outside of your body and html tags also which in a normal web page wouldn't be rendered. The problem with your HTML is you're setting up loads of tables instead of one with multiple rows. It should be like this.

<table>
 <tr>
  <td>One</td>
  <td>One.</td>
 </tr>
 <tr>
  <td>Two</td>
  <td>Two.</td>
 </tr>
 <tr>
  <td>Three</td>
  <td>Three.</td>
 </tr>
</table>

Fiddle here.. https://jsfiddle.net/fo7Ldfqs/

UPDATED:

If you've got multiple tables and you're trying to color every other one then just use:

table:nth-child(odd){background:#ff0000;}

Fiddle here.. https://jsfiddle.net/4641ph6u/

Jay
  • 1,688
  • 5
  • 20
  • 34
  • thanks that makes sense. Thanks!. Unfortunately the Plugin I use, creates 'loads of tables' (Download Manager). I provide the mark-up (HTML) for 1 'package' and when I create one page with several 'packages' the plugin creates several tables, resulting in loads of tables. – svdh May 06 '15 at 08:59
  • You mean if use the correct markup? (the one you suggested) I use the following :
    [icon] [title] [file_size] [download_url] title=" height="15" width="14"> [update_date] View details
    – svdh May 06 '15 at 10:29
  • hmm.. i'll try to clarify it: I have 10 tables, all with the same class. I would like to add alternating coloring to the tables. Table1: red Table2: white: Table3: red. and so forth.. Thanks for the tip. I use Notepad++ – svdh May 06 '15 at 13:26
  • @svdh I've updated my answer and included a fiddle. Hope it helps. – Jay May 06 '15 at 13:34
  • @svdh No problems at all. Happy to help =) Could you kindly mark this as the answer so the thread becomes closed. – Jay May 06 '15 at 14:35