4

Usually when I have floating elements inside a container div, I'll have something like this:

<div class="container">
  <div style="float: left;">content</div>
  <div style="float: left;">content</div>
  <div style="clear:both;"></div>
</div>

I find it extremely annoying and ugly to have that <div style="clear:both;"></div> on every fluid piece of layout. So I tried to do something like this (using css but, for simplicity):

<div class="container" style="clear:both;">
  <div style="float: left;">content</div>
  <div style="float: left;">content</div>
</div>

And did not work. Is it possible to make it work by adding something to the .container class??

acm
  • 6,541
  • 3
  • 39
  • 44

2 Answers2

8
.container {
    overflow: hidden; // causes the container to wrap its floated children
}
Finbarr
  • 31,350
  • 13
  • 63
  • 94
  • It only causes scollbars if you use `overflow: auto`. See http://www.w3schools.com/Css/pr_pos_overflow.asp – Finbarr Apr 06 '11 at 11:29
  • or you can float the parent container too, with a width is ususally best - and if it's default width is 100% then that saves any hidden content issues or unwanted scrollbars – clairesuzy Apr 06 '11 at 11:34
  • Floating the parent container without any width declaration causes it to perfectly shrinkwrap around the dimensions of its child elements - this is another option. – Finbarr Apr 06 '11 at 11:37
  • Interesting, so there doesn't seem to be a need for "clearfix" any more nowadays? I started a question asking to confirm this: http://stackoverflow.com/questions/5565668/in-2011-is-there-any-need-for-clearfix – Pekka Apr 06 '11 at 11:37
4

Edit: Using a clearfix is only necessary in certain cases as explained here. overflow: hidden is the superior method.

There is a technique called clearfix that does not require a clearing element, and has been built with a lot of care for cross-browser compatibility. That leads to a lot of browser-specific CSS, but that can be integrated into an existing style sheet.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088