简体   繁体   中英

Why does display:table set the parent element's height to its biggest floating child element's height?

For example, I have this these lines of codes:

<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>

And I have the following css:

.parent {
    display: table;
}

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

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

Why does it set the parent element height to the same height as "child2"? And why not when the parent element is considered as a block element (since div is displayed as block, right?)?

Also, is it acceptable to use this display:table to set a non-specified parent element's height to automatically adjust to the height of its biggest floating child element? I've read that we should avoid the use of tables unless the content truly is a table.

There's a couple of things going on. When you put non-table elements inside an element with display:table , the non-table elements are automatically wrapped in anonymous objects for table-row and table-cell. So what the layout tree sees is

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

Then, all table-cells establish block formatting contexts , which means that they contain their floats , much like using overflow:hidden on a block element without a fixed height works as sort of clearfix.

So the table-cell wholly contains the floats, the table-row contains the table-cell and the table contains the table-row. Meaning that the table will be the height of the largest float.

And yes, it's fine to use display:table like this. Just don't use real HTML tables for non-tabular data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM