31

I have a HTML table as follows:

<table border="1">
    <tr>
        <td>Row with text</td>
    </tr>
    <tr>
        <td></td><!-- Empty row -->
    </tr>
</table>

When you run this you'll see the second row is collapsed, but I'd rather it was rendered uncollapsed, with the same height as the first row. One way of doing this is to put a &nbsp; entity, as follows:

<table border="1">
    <tr>
        <td>Row with text</td>
    </tr>
    <tr>
        <td>&nbsp;</td><!-- Empty row -->
    </tr>
</table>

Is there a way I can achieve the second result, via CSS, using the HTML from the first snippet?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Dan Stevens
  • 6,392
  • 10
  • 49
  • 68

3 Answers3

44

You can use this code:

td:empty::after{
  content: "\00a0";
}

It adds escaped &nbsp; after every originally empty td, solving your issue.

td:empty::after{
  content: "\00a0";
}
<table border="1">
    <tr>
        <td>Row with text</td>
    </tr>
    <tr>
        <td></td><!-- Empty row -->
    </tr>
    <tr>
        <td>asd</td>
    </tr>
    <tr>
        <td>dees</td>
    </tr>
    <tr>
        <td></td><!-- Empty row -->
    </tr>
</table>

Learn more about escaping HTML entities here.

TylerH
  • 20,799
  • 66
  • 75
  • 101
wscourge
  • 10,657
  • 14
  • 59
  • 80
4

You can add height to table-cell, in this case it'll work like min-height property for other elements (with display: block, display: inline-block, etc). I added another table row with long text to demonstrate it:

td {
    height: 22px;
}
<table border="1">
    <tr>
        <td>Row with text</td>
    </tr>
    <tr>
        <td></td><!-- Empty row -->
    </tr>
    <tr>
        <td>Very-very long text with many words, Very-very long text with many words, Very-very long text with many words, Very-very long text with many words, Very-very long text with many words</td>
    </tr>
</table>

You can't use min-height property, because the specification says:

In CSS 2.1, the effect of 'min-height' and 'max-height' on tables, inline tables, table cells, table rows, and row groups is undefined.

sergdenisov
  • 8,327
  • 9
  • 48
  • 63
  • 1
    This solution works, but it's not as good as wscourge's solution because, depending on what you set the height to, blank rows may not be exactly the same height as non-blank rows. With wscourge's solution blank and non-blank rows are the same height. – Dan Stevens Feb 14 '17 at 17:05
  • @DanStevens yes, I agree, his solution is better =). – sergdenisov Feb 14 '17 at 17:13
0

Try adding to your table CSS formatting like

table.someclass tbody td {
      white-space:nowrap;
      min-width:30px;
      vertical-align:top;
}

This will make all empty cells equal and at least 30px wide.

Things like &nbsp;, nowrap and CSS content appending like content: "\00a0"; didn't work for me.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Alex Khimich
  • 788
  • 9
  • 10