Parent Height doesn't follow their float children

Jongz Puangput picture Jongz Puangput · May 11, 2013 · Viewed 23.9k times · Source

My mainContainer height doesn't follow their children width

and here is my code do you have any suggestion please advise.

I need the CSS solution not JavaScript so thank in advance

<div id="mainContainer">
    <div id="leftContent">

    </div>

    <div id="rightContent">

    </div>
</div>

and here is my css

#mainContainer{
    width: 1000px;
    /*height: 1000px;*/
    height:auto;
    margin-left:auto;
    margin-right:auto;
    background-color: #ff6600;
    padding-bottom: 20px;
}
#leftContent{
    height: 100px;
    float: left;
    width: 380px;
    background-color: violet;
}
#rightContent{
    height: 100px;
    float: right;
    width: 620px;
    background-color: yellow;
}

Answer

Kevin Boucher picture Kevin Boucher · May 11, 2013

Add overflow:hidden; to the container:

#mainContainer{
    width: 1000px;
    /*height: 1000px;*/
    height:auto;
    margin-left:auto;
    margin-right:auto;
    background-color: #ff6600;
    padding-bottom: 20px;

    overflow: hidden; /* <--- here */
}

Because its content is floated, the container div collapses. Using a 'clearfix' class or, as I mentioned, adding overflow:hidden will cause the container to contain the floated elements.

UPDATE Explanation of why this works can be found here: https://stackoverflow.com/a/9193270/1588648

... and here:

In order for them (browsers) to calculate what overflowed the bounds of the block (and thus should be hidden), they needed to know the size of the block. Because these blocks do no have an explicit height set, the browsers used the calculated height of the content instead.

http://www.stubbornella.org/content/2009/07/23/overflow-a-secret-benefit/