通过CSS防止HTML表中的空行折叠

Prevent collapse of empty rows in HTML table via CSS

我有一个HTML表,如下所示:

1
2
3
4
5
6
7
8
<table border="1">
    <tr>
        <td>Row with text</td>
    </tr>
    <tr>
        <td></td><!-- Empty row -->
    </tr>
</table>

运行此命令时,您会看到第二行是折叠的,但我宁愿它未折叠,且高度与第一行相同。 一种方法是放置实体,如下所示:

1
2
3
4
5
6
7
8
<table border="1">
    <tr>
        <td>Row with text</td>
    </tr>
    <tr>
        <td></td><!-- Empty row -->
    </tr>
</table>

有没有办法通过CSS使用第一个片段中的HTML来获得第二个结果?


您可以使用以下代码:

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

它在每个最初为空的td之后添加转义的,从而解决了您的问题。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<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>

在此处了解有关转义HTML实体的更多信息。


您可以向table-cell添加高度,在这种情况下,它将像其他元素的min-height属性一样工作(使用display: blockdisplay: inline-block等)。 我添加了另一个带有长文本的表格行来演示它:

1
2
3
td {
    height: 22px;
}
1
2
3
4
5
6
7
8
9
10
11
<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>

您不能使用min-height属性,因为该规范指出:

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.


尝试添加到表CSS格式,例如

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

这将使所有空单元格相等且宽度至少为30px。

nowrap和CSS内容添加(例如content:"\\00a0";)对我不起作用。