CSS: DIV containing no height on float set

RYN picture RYN · Oct 24, 2010 · Viewed 35.3k times · Source

assume we have this code:

<div id='upperDiv' style='min-height:200px;border: 1px solid #000000;'>
     <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>

When content of rightDiv and leftDiv passes the 200px height (the min height) upperDiv doesn't grow, so its content overlaps the lower div. If I remove the float attribute of the large content it grows and there will be problem. But I don't know which Div (rightDiv or leftDiv) passes 200px height. How can I fix this?

Thanks

Answer

jessegavin picture jessegavin · Oct 24, 2010

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.