CSS Best Practice #3: Clear Floated Containers (with Height||Width and Overflow)

I know you\’ve done it before. I think we\’ve all done it. You have a container with a floated element inside. The container doesn\’t wrap around everything, thus causing the element to break outside of the container. To fix this, we\’d usually add a clear element at the bottom of the container so it would wrap everything within. But there is a better solution, which uses two CSS properties. For this example, I\’ll place the styles inline.. please don\’t hate me.

If you want to just get to the better solution…

The Example

\"Alt

Text inside the container div.

Proceeding with the example, div.clear is placed at the bottom of div.container, which solves the problem. Div.container\’s border now wraps all the elements within.

\"Alt

Text inside the container div.

The Better Solution

But why should we even bother placing an extra element? It\’s not sexy. Here\’s the solution: Use height:1% or width:100% and overflow:auto||hidden on div.container. Height and width on div.container would set the hasLayout property in IE, thus fixing a slew of float/box-model bugs (more on hasLayout). Overflow auto or hidden tells div.container to wrap everything within it.

Note: This won\’t work if the element is floated, which would cause it to shrink to the percentage height or width.

The HTML

\"Alt

Text inside the container div.

The CSS

div.container {height:1%; overflow:hidden;}

8 thoughts on “CSS Best Practice #3: Clear Floated Containers (with Height||Width and Overflow)”

    1. @Christoph and @Jarryd:
      Thanks for your input. I believe it’s all personal preference. If anything I would use invalid techniques/methods as a last resort. So yes, I could use zoom:1 to evoke hasLayout, but I would first exhaust all other methods.

      @Maxwell:
      Hey, I’m glad it was helpful! Awesome work with Animevice btw.

  1. @Jarryd: Totally agree with you. Web standards are a must, but not to the point at which they start to hinder the implementation of advanced designs- and interaction techniques. So if there’s e non-standard workaround for some stupid IE bugs, let’s embrace it and forget about the rest.

  2. Wenn ich es nicht besser wissen würde, dann würde ich ohne zu zögern darauf tippen, dass dieser Artikel “CSS Best Practice #3: Clear Floated Containers (with Height||Width and Overflow) | Garrick Cheung”
    glatt von mir verfasst wurde so gelungen wie
    der verfasst wurde. Alle Finger nach oben und weiterhin viel Erfolg weiter so in Zukunft!

Leave a Reply

Your email address will not be published. Required fields are marked *