Prevent collapse of empty rows in HTML table via CSS

回眸只為那壹抹淺笑 提交于 2020-06-10 07:24:07

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/42225196/prevent-collapse-of-empty-rows-in-html-table-via-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!