1

There're dozens of ways to clear float in order to make sure the containing block containing all his descendents including floating children.

  1. using markup:<div style="clear:both;"></div>
  2. Creating a new block formatting context:
    • is floated
    • is absolutely positioned
    • has a display property value of one of more unusual properties(table-cell,etc.)
    • overflow

My Question is : is there any other method?

Many thanks for helping!

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
eileen Tao
  • 1,023
  • 1
  • 8
  • 8

3 Answers3

4

Some methods you didn't cover in your question:

  • display: inline-block - I wouldn't really count that as "an unusual display value", although it's not usually used to clear floats because of it's side effects (such as shrink-wrapping): http://jsfiddle.net/CLXbc/
  • The clearfix class - this is a common technique - http://jsfiddle.net/CLXbc/1/

    /* The Magnificent Clearfix: Updated to prevent margin-collapsing on child elements.
       j.mp/bestclearfix */
    .clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; overflow: hidden; }
    .clearfix:after { clear: both; }
    /* Fix clearfix: blueprintcss.lighthouseapp.com/projects/15318/tickets/5-extra-margin-padding-bottom-of-page */
    .clearfix { zoom: 1; }
    

By far the two most common methods are overflow: hidden and clearfix.

Going through your other options, here's why they aren't optimal:

  • "using markup:<div style="clear:both;"></div>" - this is not semantic. Splattering clearing divs throughout your HTML is a poor choice.
  • "is floated" - this works, but you don't usually want the shrink-wrapping.
  • "is absolutely positioned" - you don't usually want your element to be absolutely positioned.
  • "has a display property value of one of more unusual properties(table-cell,etc.)" - display: table-cell doesn't work in IE7.. and yet again, you don't want the side effects.

I use overflow: hidden in most cases. Sometimes I can't use that, for example here. In those cases, I usually fallback to clearfix.

Community
  • 1
  • 1
thirtydot
  • 224,678
  • 48
  • 389
  • 349
0

You can set the floating element's parent element to overflow:hidden; or overflow:auto;.

http://www.quirksmode.org/blog/archives/2005/03/clearing_floats.html

peterp
  • 3,145
  • 1
  • 20
  • 24
0

Here's a great read about Floats. Might even give some more insight to long time web developers as well.

http://css-tricks.com/all-about-floats/

red
  • 1,980
  • 1
  • 15
  • 26