Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 873
dima1109 Avatar asked Jan 29 '14 15:01

dima1109


People also ask

How do I make my div take 100% height of parent div?

container div has two parent elements: the <body> and the <html> element. And we all know that the default value of the height property is auto , so if we also set the height of <body> and <html> elements to 100%, the resulting height of the container div becomes equal the 100% height of the browser window.

How do I make DIVS always fit in my parent div?

Method 1: First method is to simply assign 100% width and 100% height to the child div so that it will take all available space of the parent div. Consider this HTML for demonstration: HTML.


1 Answers

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)

like image 111
kapa Avatar answered Oct 26 '22 13:10

kapa