为什么 display:table 将父元素的高度设置为其最大浮动子元素的高度?
Why does display:table set the parent element's height to its biggest floating child element's height?
例如,我有这些代码行:
<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}
为什么它把父元素的高度设置成和"child2"一样的高度?为什么不当父元素被视为块元素时(因为 div 显示为块,对吗?)?
另外,是否接受table使用这个display:table设置一个非指定父元素的高度 自动调整其最大浮动子元素的高度?我读到我们应该避免使用 tables 除非内容确实是 table.
发生了几件事。当您将非 table 元素放入具有 display:table
的元素内时,对于 table-row 和 [=],非 table 元素将自动包装在 anonymous objects 中25=]-细胞。所以布局树看到的是
table
- table-row
- table-cell
- child1
- child2
- child3
然后,所有 table-cells 建立 block formatting contexts, which means that they contain their floats,就像在没有固定高度的块元素上使用 overflow:hidden
一样。
所以 table 单元格完全包含浮点数,table 行包含 table 单元格,table 包含 table -排。这意味着 table 将是最大浮动的高度。
是的,可以这样使用 display:table
。只是不要对非表格数据使用真正的 HTML 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}
为什么它把父元素的高度设置成和"child2"一样的高度?为什么不当父元素被视为块元素时(因为 div 显示为块,对吗?)?
另外,是否接受table使用这个display:table设置一个非指定父元素的高度 自动调整其最大浮动子元素的高度?我读到我们应该避免使用 tables 除非内容确实是 table.
发生了几件事。当您将非 table 元素放入具有 display:table
的元素内时,对于 table-row 和 [=],非 table 元素将自动包装在 anonymous objects 中25=]-细胞。所以布局树看到的是
table
- table-row
- table-cell
- child1
- child2
- child3
然后,所有 table-cells 建立 block formatting contexts, which means that they contain their floats,就像在没有固定高度的块元素上使用 overflow:hidden
一样。
所以 table 单元格完全包含浮点数,table 行包含 table 单元格,table 包含 table -排。这意味着 table 将是最大浮动的高度。
是的,可以这样使用 display:table
。只是不要对非表格数据使用真正的 HTML tables。