5

I am building an app and I have a table dynamically created.

The table rows are created as follows

<tr style="background-color: #71aa9a;">
  <td></td>
  .
  . 
  .
  <td></td>
<tr/>

And some of the td's are hidden during creation .

The problem that arises is that when a td is invisible (visibility:hidden) the background color of tr is disappeared and is white instead.

Can someone explain me why and how can i solve it ?

I dont want to use display:none; due to the need of specific td's in a row.

3
  • 2
    opacity: 0; work as an alternative but I don't have the why Aug 24, 2018 at 13:38
  • 1
    Here's a fiddle with the situation: jsfiddle.net/7cs1zhLd/1 I get the issue in Firefox but not Chrome. It really feels like background color applied to tr is in fact applied directly to td, but finding some reference about this would be neat.
    – lampyridae
    Aug 24, 2018 at 13:46
  • 1
    In each table cell wrap content in a div and apply css on it as a workaround.
    – Stickers
    Aug 24, 2018 at 14:30

2 Answers 2

3

I'm sorry I don't have a more definitive explanation about the issue, but the fact is that background properties on <tr> elements are finicky. If I was you I'd just wrap cell content in a <div> and do visibility: hidden on that instead.

<tr>
  <td><div style="visibility: hidden">You dont see me!</div></td>
  <td>etc.</td>
</tr>
0
2

Okay, I'd use trick using mainly font-size: 0, which will make content invisible, unselectable. Styles for all inner elements (>*) are here to overwrite default values.

Snippet

tr {
  background: red;
}

.hidden,
.hidden>* {
  font-size: 0;
  height: 0;
  width: 0;
  margin: 0;
  border: 0;
  background: transparent;
}
<table>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td class="hidden"><button onclick="">Smith</button></td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

5
  • 3
    Making the cell's content transparent does not prevent the content from being selected and copy-pasted, nor does it prevent links or buttons from being clicked.
    – lampyridae
    Aug 24, 2018 at 13:54
  • Plus I have buttons in it that can be clicked. But thank you for the response Aug 24, 2018 at 14:10
  • @lampyridae : that's right, but if you have any other solution w/o JS I'm all ears. Aug 24, 2018 at 14:27
  • Okay, I've edited my answer. New trick should do the job in all cases. Aug 24, 2018 at 14:37
  • Using font-size: 0; background-color: black; works for me. It retains my background color. Using visibility: hidden removes background color.
    – kohane15
    Nov 12, 2020 at 8:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.