How do I properly set the background colour of tbody elements in a table?

817 Views Asked by At

I have a table consisting of multiple tbody elements that consist of multiple tr rows:

<table>
    <thead>[...]</thead>
        <tbody>
            <tr><td></td></tr>
            <tr><td></td></tr>
        </tbody>
        <tbody>
            <tr><td></td></tr>
            <tr><td></td></tr>
        </tbody>

        &c...

</table>

When trying to give children tbody elements of table a background colour (using table tbody:nth-child(even){}), only part of the entire tbody element is coloured (namely the individual cells). The background colour of the table is always partially shining through.

How can I get an even tbody field of a single colour, so the different elements can easily be told apart?

I stumbled upon this thread (Why doesn't `tbody` set the background color in a table?) during my search, and the title implicates the exact same problem, but the rest of that question is more specific and actually about getting border-radius to cooperate with the set background color.

1

There are 1 best solutions below

0
On BEST ANSWER

As the borders of the table element are the culprit here, we need to get rid of those:

  • Add cellspacing='0' cellpadding='0' to your table html code (<table cellspacing='0' cellpadding='0'>).
  • Add border:none to your table's CSS.

Now the table should render properly, without any other-coloured lines crossing through, but we might want to reintroduce the spaces surrounding the elements.
The easiest way to achieve this is to give the td element some padding (e.g. table tbody td {padding-top:1em}). As this won't interfere with the set background colour of the tbody elements, this can be used to realign and re-space your table.