I’ve learned a lot of fun little tidbits in my time here at dt. One of my favorite insights has to do with clearing floated elements. There are several ways of dealing with this issue. I used to add an empty div with “clear: both” just under the floating element.

The Better Way to Fix it

But, there’s a simpler and more efficient way to address this issue. By placing a little bit of CSS on the containing element, the height of the floating elements are magically detected.

width: 100%; (any width definition besides “auto” will work)
position: relative;
overflow: hidden;

Create a class of “container” and add that class to whatever needs to be cleared. Unfortunately the “overflow:hidden;” means you won’t be able to use positioning or margins to push elements outside of their container, so just be sure to plan ahead.

Why Does This Matter?

Code is all about being efficient. This solution is quicker for coding since it’s just an additional class and there aren’t anymore empty divs taking up space in the html. That means there’s less code to load, less to sort through when doing edits and updates, and it’s very modular.

Reblog this post [with Zemanta]
  • Jeff Dion

    I used to use this technique until i had to print out long pages with overflow:hidden. After a while i started to use a

    @media screen{
    overflow :hidden

    This worked well for a while but started to make my css look a bit akward or i had to use a media print css without that line.

    Now i am using the clearfix method which require a class to be added to the element

    • Thanks for the link Jeff, I’ll check this out. At first glance it does seem a bit verbose. There’s definitely a balancing act in figuring out how bullet proof your code is and how complicated it is to get that result.

  • Nice tip, seems more bullet-proof than some of the other methods out there.

  • Joe

    This code works better and is more efficient

    .container {
    float: left;
    display: inline;

  • Yep. Most frameworks add this via a .clearfix class now.