CSS: DIV containing no height on float set
Given the following code:
<div id='upperDiv' style='min-height:200px'>
<div id='rightDiv' style='float:right; width:75%'>
content1
</div>
<div id='leftDiv' style='float:left; width:25%'>
content2
</div>
</div>
<div id='low开发者_StackOverflow中文版erDiv' style='height:50px; margin-top:5px'>
content3
</div>
When content of rightDiv
and leftDiv
passes the 200px height (the value of min-height
), upperDiv
does not grow, so its content overlaps the lower div.
If the float attribute is removed from the large content, it grows and causes problems.
I do not know which of rightDiv
or leftDiv
exceeds 200px inheight.
How can this be fixed?
Set #upperDiv
any of the following:
overflow: hidden;
width: 100%;
or
float: left;
width: 100%;
or create a rule using CSS pseudo-elements (IE8+ compatible) like this
#upperDiv:after {
content: "";
display: table;
clear: both;
}
Best solution
Creating a reusable class rule like the following.
.group:after {
content: "";
display: table;
clear: both;
}
Now you can apply it to anything that needs this same functionality. For example...
<div id='upperDiv' class="group" ... >
P.S. If you require IE 6/7 compatibility, checkout this post.
This is intentional as floats are designed for things like images in paragraphs (where multiple paragraphs can wrap around the image).
Complex Spiral has a fuller explanation as to why and Ed Elliot describes a number of approaches to making containers expand around floats. I find the overflow: hidden
approach works best in most situations.
After
<div id='leftDiv' style='float:left;width:25%;'> content2 </div>
add
<div style="clear:both"></div>
It will solve your problem.
There is a new property introduced recently display: flow-root;
Which will fix this issue without any hacks and have almost all major support
<div id='upperDiv' style='border: 1px solid #000000; display: flow-root;'>
<div id='rightDiv' style='float:right;width:75%;'>
content1
</div>
<div id='leftDiv' style='float:left;width:25%;'>
content2
</div>
</div>
<div id='lowerDiv' style='height:50px;border: 1px solid #000000;margin-top:5px;'>
content3
</div>
精彩评论