为什么display:table将父元素的高度设置为其最大浮动子元素的高度?

时间:2018-05-18 06:21:57

标签: html css css-tables

例如,我有这些代码行:

<div class = "parent">
    <div class = "child1">Hello</div>
    <div class = "child2">This child element has the biggest height</div>
    <div class = "child3">Just another ordinary class</div>
</div>

我有以下css:

.parent {
    display: table;
}

.child1, .child2, .child3 {
    float: left;
}

.child1 {height: 200px}
.child2 {height: 1000px}
.child3 {height: 500px}

为什么将父元素高度设置为&#34; child2&#34;?为什么不将父元素视为块元素(因为div显示为块,对吧?)?

此外,使用此display:table是否可以设置未指定的父元素的高度以自动调整到其最大的高度漂浮儿童元素?我已经读过我们应该避免使用表格,除非内容确实是一个表格。

1 个答案:

答案 0 :(得分:1)

有几件事正在发生。当您将非表元素放在具有display:table的元素内时,非表元素将自动包装在anonymous objects中,用于表行和表格单元格。那么布局树看到的是

table
  - table-row
      - table-cell
          - child1
          - child2
          - child3

然后,所有表格单元格都建立block formatting contexts,这意味着它们contain their floats就像在没有固定高度的块元素上使用overflow:hidden一样,可以作为一种clearfix。

因此表格单元格完全包含浮点数,表格行包含表格单元格,表格包含表格行。这意味着该表将是最大浮点数的高度。

是的,可以像这样使用display:table。只是不要使用真正的HTML表格来表示非表格数据。

相关问题