HTML div elements not taking the height of their parent, even though the parent has nonzero height
Asked Answered
O

2

9

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.

Orchestrion answered 29/1, 2014 at 15:13 Comment(3)
Add min-height to child2 nd then set it upDefamation
For height: 100% to work, "container" needs to have an explicit height set. This is not the case. Its height is implicitely given by its content - i.e. the table.Sculpturesque
This might help: #18362526Addressee
S
24

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)

Stipel answered 29/1, 2014 at 15:17 Comment(2)
and what if the container is a TD? how to do it?Sandra
@RogerOliveira I am sure there is a question here with multiple solutions, if not, you could ask oneStipel
S
4

Or you could use: aspect-ratio This safe me a lot of headache :)

Sarcastic answered 7/9, 2023 at 14:59 Comment(2)
Pretty good first answer. An example would make it better!Tonsorial
thanks. worked for me like a charm, i just used aspect-ration: 1/2 and it took the whole height of the parent, I do not understand how it works, but it just does.Clouded

© 2022 - 2024 — McMap. All rights reserved.