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; }
Method 1 (Using Overflow Property): We can use the overflow property of CSS to prevent the parents from collapsing. Set the value of the overflow property as “auto” for the parent and it will not collapse any more.
"For one, the box being floated should have a width defined for it, either explicitly or implicitly. Otherwise, it will fill its containing block horizontally, just like non-floated content, leaving no room for other content to flow around it.
CSS float is a property that forces any element to float (right, left, none, inherit) inside its parent body with the rest of the element to wrap around it. This property can be used to place an image or an element inside its container and other inline elements will wrap around it.
The CSS float property controls the positioning and formatting of content on the page. Its most common use is to wrap text around images. However, you can use the float property to wrap any inline elements around a defined HTML element, including lists, paragraphs, divs, spans, tables, iframes, and blockquotes.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With