Search code examples
csshtmlheight

How to make a floated div 100% height of its parent?


Here is the HTML:

<div id="outer">
    <div id="inner"></div>
    Test
</div>

And here is the CSS:

#inner {
  float: left;
  height: 100%;
}

Upon inspection with the Chrome developer tools, the inner div is getting a height of 0px.

How can I force it to be 100% of the height of the parent div?


Solution

  • For #outer height to be based on its content, and have #inner base its height on that, make both elements absolutely positioned.

    More details can be found in the spec for the css height property, but essentially, #inner must ignore #outer height if #outer's height is auto, unless #outer is positioned absolutely. Then #inner height will be 0, unless #inner itself is positioned absolutely.

    <style>
        #outer {
            position:absolute; 
            height:auto; width:200px; 
            border: 1px solid red; 
        }
        #inner {
            position:absolute; 
            height:100%; 
            width:20px; 
            border: 1px solid black; 
        }
    </style>
    
    <div id='outer'>
        <div id='inner'>
        </div>
        text
    </div>
    

    However... By positioning #inner absolutely, a float setting will be ignored, so you will need to choose a width for #inner explicitly, and add padding in #outer to fake the text wrapping I suspect you want. For example, below, the padding of #outer is the width of #inner +3. Conveniently (as the whole point was to get #inner height to 100%) there's no need to wrap text beneath #inner, so this will look just like #inner is floated.

    <style>
        #outer2{
            padding-left: 23px;
            position:absolute; 
            height:auto; 
            width:200px; 
            border: 1px solid red; 
        }
        #inner2{
            left:0;
            position:absolute; 
            height:100%; 
            width:20px; 
            border: 1px solid black; 
       }
    </style>
    
    <div id='outer2'>
        <div id='inner2'>
        </div>
        text
    </div>
    

    I deleted my previous answer, as it was based on too many wrong assumptions about your goal.