簡體   English   中英

為什么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顯示為塊,對嗎?)?

另外,可以使用此display:table來設置未指定的父元素的高度以自動調整為其最大的浮動子元素的高度嗎? 我讀過,除非內容真正是表格,否則我們應該避免使用表格。

發生了幾件事。 當您使用display:table將非表元素放入元素display:table ,非表元素會自動包裝在匿名對象中,用於表行和表單元格。 所以布局樹看到的是

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

然后,所有表單元格都建立塊格式化上下文 ,這意味着它們包含它們的浮點數 ,就像在沒有固定高度的情況下在塊元素上使用overflow:hidden一樣。

因此,表單元格完全包含浮點數,表行包含表單元格,而表包含表行。 這意味着表格將是最大浮點數的高度。

是的,可以像這樣使用display:table 只是不要對非表格數據使用真實的HTML表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM