为什么 table-caption 会增加 table 的高度?

Why does table-caption increase the height of the table?

两个 table 的高度都设置为 50px,并且它们的内容没有溢出。但是带标题的 table 实际上是 70px,因为标题似乎没有包含在 table 的高度计算中。

任何人都可以解释在计算 table 高度时不包括标题的理由吗?

毕竟是 table 的 child。如果你想将它从 table 高度中排除,如果你不想包含它,可以将标题 放在 之外 table。

.table {
  display: table;
  height: 50px;
}
.table-caption {
  display: table-caption;
  background-color: red;
  height: 20px;
}
.table-row {
  display: table-row;
  background-color: green;
}
.table-cell {
  display: table-cell;
}
<div class="table">
  <div class="table-row">
    <div class="table-cell">table height is 50px</div>
  </div>
</div>

<br>
  
<div class="table">
  <div class="table-caption">caption</div>
  <div class="table-row">
    <div class="table-cell">table height is 70px</div>
  </div>
</div>

这在 17.4 Tables in the visual formatting model

中有解释

the table generates a principal block box called the table wrapper box that contains the table box itself and any caption boxes

也就是说,当您在带有 display: table 的元素上设置 height: 50px 时,它适用于 table 框本身,不包括标题。

table 包装框包含它,因此它的高度是 table 框本身的高度 (50px) 加上标题的高度 (20px), 即70px.

根据规范,标题实际上位于 table 框的上方或下方。因此,它从 table.

上指定的高度移除

17.4.1 Caption position and alignment

This property specifies the position of the caption box with respect to the table box.

Values have the following meanings:

top

Positions the caption box above the table box.

bottom

Positions the caption box below the table box.

Diagram of a table with a caption above it.

source: https://www.w3.org/TR/CSS2/tables.html#model