Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't `tbody` set the background color in a table?

I am using <tbody> as a CSS selector to set the background-color in a table. I'm doing this because I have multiple <tbody> sections within the table, and they have different background colors.

My issue is that when using border-radius on the cells, the cell doesn't respect the background-color of the tbody. That is, the border radius cuts out the corners in the default background color (in this case white), not the tbody color (in this case, green), below.

UPDATE: This problem occurs in Chrome/Safari, but not in Firefox (just tested myself on all 3). Still looking for a workaround on Chrome (FOUND! See accepted answer).

tr:first-child td:first-child {
  background-color: red;
  border-radius: 25px;
}

table {
  border-spacing: 0px;
}

table tbody {
  background-color: green;
}
<table>
  <tbody>
    <tr>
      <td><p>TOP LEFT</p></td>
      <td><p>TOP RIGHT</p></td>
    </tr>
    <tr>
      <td><p>BOT LEFT</p></td>
      <td><p>BOT RIGHT</p></td>
    </tr>
  </tbody>
</table>

To be clear, the fix I'm looking for would change the resultant example so it looks like this (I'm just changing the table tbody selector to table only):

tr:first-child td:first-child {
  background-color: red;
  border-radius: 25px;
}

table {
  border-spacing: 0px;
}

table { /* changed this line */
  background-color: green;
}
<table>
  <tbody>
    <tr>
      <td><p>TOP LEFT</p></td>
      <td><p>TOP RIGHT</p></td>
    </tr>
    <tr>
      <td><p>BOT LEFT</p></td>
      <td><p>BOT RIGHT</p></td>
    </tr>
  </tbody>
</table>

I don't want to do it that way, because I want the background-color to be on the tbody (which I have multiple ones) NOT on the whole table.

Any way to make the tbody color show through?

like image 676
Brian Avatar asked Jan 15 '16 18:01

Brian


2 Answers

Try making the <tbody> to render like a block element.

tbody {
  background-color: green;
  display: block;
}

tr:first-child td:first-child {
  background-color: red;
  border-radius: 25px;
}
table {
  border-spacing: 0px;
}
tbody {
  background-color: green;
  display: block;
}
<table>
  <tbody>
    <tr>
      <td><p>TOP LEFT</p></td>
      <td><p>TOP RIGHT</p></td>
    </tr>
    <tr>
      <td><p>BOT LEFT</p></td>
      <td><p>BOT RIGHT</p></td>
    </tr>
  </tbody>
</table>
like image 189
Stickers Avatar answered Oct 06 '22 19:10

Stickers


An updated answer for other users, if it helps.

On Chrome, the display: block fixes the issue. However, it causes other layout issues with the table, where it does not seem to respect widths. Using display: table instead seems to resolve both issues:

tbody {
  background-color: green;
  display: table;
}
like image 4
Brian Avatar answered Oct 06 '22 18:10

Brian