How to make div height increase to include floated image

Viewed 16842

This is the problem. I have an div which includes a few paragraphs of text in it and then an image which is floated right. The image floats right as it should but the containing div does not expand vertically to accommodate for the image. I know that I can manually set the height of the div but this becomes problematic because I would like to use this same div for each page of my site and thus the heights will need to be different.

Here is a code sample:

#main_contentbox {
  width: 918px;
  margin: 10px auto;
  padding: 10px 20px 20px 20px;
  background-color: #ffffff;
  border-style: solid;
  border-width: 1px;
  border-color: #000;
}

#main_contentbox img#sample {
  float: right;
}
<div id="main_contentbox">
  <h1 class="page"> The Event </h1>
  <img id="sample" src="sample.jpg" />
  <p>
    stackoverflow is awesome!stackoverflow is awesome!stackoverflow is awesome!stackoverflow is awesome!stackoverflow is awesome!stackoverflow is awesome!stackoverflow is awesome!</p>

  <p>stackoverflow is awesome!stackoverflow is awesome!stackoverflow is awesome!stackoverflow is awesome!


</div>

4 Answers

You can change the behaviour of how parent blocks deal with floated content by changing the overflow property. This should do it:

#main_contentbox { overflow: hidden; }

Using an :after pseudoclass, you can have the named div automatically append a clear fix. Add this to your css file:

#main_contentbox:after {
  content: "Foo";
  visibility: hidden;
  display: block;
  height: 0px;
  clear: both;
}

With that in place, you don't have to do anything to force main_contentbox to grow to contain its floats, no matter what page you're on.

Try something with JavaScript maybe:

window.onload = FixMyDiv();

function FixMyDiv()
{
  var divh = document.getElementById('main_contentbox').style.offsetHeight;
  var imgh = document.getElementById('sample').style.offsetHeight;

  if(divh < imgh + 50) document.getElementById('main_contentbox').style.height = imgh + 50;


}
Related