HTML div elements not taking the height of their p

2019-03-31 14:21发布

问题:

I have a fairly simple problem. I have a container div with three children - two divs and a table. The following is the CSS:

#container {
   overflow: auto;
}
#child1 {
   float: left;
   width: 50px;
   height: 100%;
}
#table1 {
   float: left;
}
#child2 {
   float: left;
   width: 50px;
   height: 100%;
}

The HTML is very simple as well

  <div id='container'>
      <div id='child1'></div>
      <table id='table1'>
        <tbody></tbody>
      </table>
      <div id='child2'></div>
  </div>

The table has some content that sets its height. When the page is rendered, the height of the parent container div is set to the height of the table, as it should. The other children, however, are being collapsed for some reason. Here's the example, with some table elements and styling for clarity: http://jsfiddle.net/GUEc6/. As you see, the height of the container div is being properly set to the height of the table, but the child1 and child2 divs fail to properly set their heights to 100% of that. I know that if a floated element has its height set to 100%, the parent element needs to have some definition of its own height so the child can be 100% of something concrete. But it doesn't look like that's what's happening here.

回答1:

It's a common misconception about height: 100%.

From MDN:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to auto. A percentage height on the root element is relative to the initial containing block.

One solution to your problem could be absolute positioning. Set position: relative on your container and position the children absolutely. Setting top: 0; bottom: 0; on them will stretch them to the container's height.

Quick Demo (shows the concept, you might need to tweak it)