Wednesday, October 17, 2012

Retain Height of Floated Elements

A very common thing that a developer moving away from tables will want to do is float divs next to each other. This is a great way to display elements side by side but one fall back is they lose there block height causing other content to come up from beneath them. There is a simple fix to this problem that I would like to show today.

The HTML

<div id="container">
   <div id="floatLeft">
       <p>I want to keep this elements height.</p>
   </div>
   <div id="floatRight">
       <p>I want to keep this elements height as well.</p>
   </div>
</div>

The fix is setting the parent div of both floated elements overflow property to hidden/auto.

The CSS

#container{
  width: 960px;
  margin: 0px auto;
  overflow: hidden;
}
#floatLeft{
  float: left;
  width: 480px;
}
#floatRight{
  float: right;
  width: 480px;
}

No comments:

Post a Comment