By Chris J Allen


2008-10-17 08:15:36 8 Comments

I have the age-old problem of a div wrapping a two-column layout. My sidebar is floated, so my container div fails to wrap the content and sidebar.

<div id="container">
  <div id="content"></div>
  <div id="sidebar"></div>
</div>

There seem to be numerous methods of fixing the clear bug in Firefox:

  • <br clear="all"/>
  • overflow:auto
  • overflow:hidden

In my situation, the only one that seems to work correctly is the <br clear="all"/> solution, which is a little bit scruffy. overflow:auto gives me nasty scrollbars, and overflow:hidden must surely have side effects. Also, IE7 apparently shouldn't suffer from this problem due to its incorrect behaviour, but in my situation it's suffering the same as Firefox.

Which method currently available to us is the most robust?

29 comments

@Mohamed Aasif 2019-07-17 10:47:15

It is so simple clearfix clears the issue by when we using the float properties inside the div element.If we use two div elements one as float:left; and other one as float:right; we can use clearfix for the parent of the two div element. If we refuse to use clearfix unnecessary spaces fill with contents below and site structure will be broken.

@Musa Butt 2013-03-15 16:24:49

.clearFix:after { 
    content: "";
    display: table;  
    clear: both;  
}

@Beau Smith 2009-10-27 19:37:01

Depending upon the design being produced, each of the below clearfix CSS solutions has its own benefits.

The clearfix does have useful applications but it has also been used as a hack. Before you use a clearfix perhaps these modern css solutions can be useful:


Modern Clearfix Solutions


Container with overflow: auto;

The simplest way to clear floated elements is using the style overflow: auto on the containing element. This solution works in every modern browsers.

<div style="overflow: auto;">
  <img
    style="float: right;"
    src="path/to/floated-element.png"
    width="500"
    height="500"
  > 
  <p>Your content here…</p>
</div>

One downside, using certain combinations of margin and padding on the external element can cause scrollbars to appear but this can be solved by placing the margin and padding on another parent containing element.

Using ‘overflow: hidden’ is also a clearfix solution, but will not have scrollbars, however using hidden will crop any content positioned outside of the containing element.

Note: The floated element is an img tag in this example, but could be any html element.


Clearfix Reloaded

Thierry Koblentz on CSSMojo wrote: The very latest clearfix reloaded. He noted that by dropping support for oldIE, the solution can be simplified to one css statement. Additionally, using display: block (instead of display: table) allows margins to collapse properly when elements with clearfix are siblings.

.container::after {
  content: "";
  display: block;
  clear: both;
}

This is the most modern version of the clearfix.


Older Clearfix Solutions

The below solutions are not necessary for modern browsers, but may be useful for targeting older browsers.

Note that these solutions rely upon browser bugs and therefore should be used only if none of the above solutions work for you.

They are listed roughly in chronological order.


"Beat That ClearFix", a clearfix for modern browsers

Thierry Koblentz' of CSS Mojo has pointed out that when targeting modern browsers, we can now drop the zoom and ::before property/values and simply use:

.container::after {
    content: "";
    display: table;
    clear: both;
}

This solution does not support for IE 6/7 …on purpose!

Thierry also offers: "A word of caution: if you start a new project from scratch, go for it, but don’t swap this technique with the one you have now, because even though you do not support oldIE, your existing rules prevent collapsing margins."


Micro Clearfix

The most recent and globally adopted clearfix solution, the Micro Clearfix by Nicolas Gallagher.

Known support: Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+

.container::before, .container::after {
  content: "";
  display: table;
}
.container::after {
  clear: both;
}
.container {
  zoom: 1;
}

Overflow Property

This basic method is preferred for the usual case, when positioned content will not show outside the bounds of the container.

http://www.quirksmode.org/css/clearing.html - explains how to resolve common issues related to this technique, namely, setting width: 100% on the container.

.container {
  overflow: hidden;
  display: inline-block;
  display: block;
}

Rather than using the display property to set "hasLayout" for IE, other properties can be used for triggering "hasLayout" for an element.

.container {
  overflow: hidden;
  zoom: 1;
  display: block;
}

Another way to clear floats using the overflow property is to use the underscore hack. IE will apply the values prefixed with the underscore, other browsers will not. The zoom property triggers hasLayout in IE:

.container {
  overflow: hidden;
  _overflow: visible; /* for IE */
  _zoom: 1; /* for IE */
}

While this works... it is not ideal to use hacks.


PIE: Easy Clearing Method

This older "Easy Clearing" method has the advantage of allowing positioned elements to hang outside the bounds of the container, at the expense of more tricky CSS.

This solution is quite old, but you can learn all about Easy Clearing on Position Is Everything: http://www.positioniseverything.net/easyclearing.html


Element using "clear" property

The quick and dirty solution (with some drawbacks) for when you’re quickly slapping something together:

<br style="clear: both" /> <!-- So dirty! -->

Drawbacks

  • It's not responsive and thus may not provide the desired effect if layout styles change based upon media queries. A solution in pure CSS is more ideal.
  • It adds html markup without necessarily adding any semantic value.
  • It requires a inline definition and solution for each instance rather than a class reference to a single solution of a “clearfix” in the css and class references to it in the html.
  • It makes code difficult to work with for others as they may have to write more hacks to work around it.
  • In the future when you need/want to use another clearfix solution, you won't have to go back and remove every <br style="clear: both" /> tag littered around the markup.

@David Rivers 2010-12-02 22:12:09

It's not ideal to use hacks, but the :after method is a hack too! So, why not use the underscore method instead of the :after method? It's shorter!

@Beau Smith 2011-01-09 23:45:54

@David Rivers: The :after method is not a hack as it doesn't exploit a parsing error in a browser, it uses a feature of css as a solution. Additionally :after will be supported in future browsers, unlike the underscore hack. Ideally there will be a css property that can be applied to an element which will cause it to contain all it's content.

@Aneon 2011-10-15 15:25:06

Thanks for the breakdown. I find the :after "easy clearing" method superior to "overflow: hidden", as it doesn't crop CSS3 box shadows or positioned elements. The extra lines of code are definitely worth it.

@kasimir 2011-11-03 12:47:09

Just out of curiosity: why would overflow: hidden; be logical? I mean: what it implies is, that content that's too big to fit, will not be shown. While what we're generally doing here, is making sure the container stretches enough to envelop all content, even floating elements. This shows more and doesn't hide anything...

@amateur barista 2012-01-20 06:12:28

I switched from Perishable Press New Clearfix hack (comes gratis with Drupal 7) to Nicolas Gallagher's Micro Clearfix hack after having some inconsistency issues across all major browsers and operating systems. It works like a charm. Thank you very much for the references, they where very useful.

@Vigrond 2012-02-12 00:16:07

I'm not advocating the br clear:both solution, but I disagree with your 'dirty' labeling of it. The 'adding weight/load slower' argument seems silly, as it's 1 short line of html code, compared to the several lines of CSS (which your browser has to load too). For the 'semantic value' argument, a br with clear:both is far easier to understand than trying to figure out a bunch of goofy firing squad css. br clear:both is short and simple, and imho has no effect on 'professionalism'.

@Beau Smith 2012-03-05 19:34:58

@Vigrond - Your point breaks down when it comes to large sites. Given the choice between 1000 clearing <br> tags or a few lines of css… I'm gonna choose the "cleaner" solution.

@Chris Calo 2012-03-29 18:23:28

There's no need for overflow: hidden.

@BoltClock 2012-07-29 13:59:20

Contrary to popular belief, overflow: hidden or overflow: auto doesn't clear floats (categorizing it as "clearfix" is a misnomer); instead it causes an element to create a new formatting context within which the floats can be contained. This causes the container to stretch to the height of the floats in order to contain them. There is no clearance involved whatsoever - that being said, you can still choose to clear, or not clear, the floats within the container depending on your layout.

@iono 2013-04-19 07:31:55

We should not be supporting IE7 any more. Please update this with the three-line method described here

@wssbck 2013-09-29 16:59:43

@tomeoftom Supporting IE7 is not always the developer's choice. Unfortunately there are still projects out there that demand support for legacy IE versions, whether we like it or not.

@iono 2013-10-02 03:42:54

@MichałGancarski Those projects, if offered, should be declined. Please see my full answer below.

@Gavin 2014-01-10 16:58:47

The last method using a BR tag is a single, small HTML tag and you're complaining that it adds file size to the HTML file, while your other solutions are multiple lines of CSS and still require class="clearfix" in the HTML if you plan on using it more than once. Yeah, it's not pretty and clean, but neither are most of the other hacks developers need to use on a daily basis to get their site looking nice in all browsers. The BR solution is cross-browser compatible, backwards compatible, and very lightweight. You shouldn't disregard it just because it's not pure CSS.

@Beau Smith 2014-01-10 22:12:39

@Gavin - the problem with the <br> solution is that you're putting presentation in your markup. This makes reusing the markup more difficult if you don't want the <br> in another context. Answer updated.

@Jack Tuck 2014-07-22 17:41:59

Regarding the 'Beat That ClearFix' solution, is display:table necessary, or is it interchangeable with display:block?

@Beau Smith 2014-07-26 07:20:16

@JackWilliam - "The use of table rather than block is only necessary if using :before to contain the top-margins of child elements." (source: nicolasgallagher.com/micro-clearfix-hack)

@David Fariña 2015-07-03 18:00:57

How about writing correct css to avoid any workarounds?

@Faust 2015-07-27 17:00:33

overflow-y:hidden (instead of overflow:hidden), reduces one more side-effect of that approach.

@Philipp Michael 2015-09-09 12:50:22

Is the ":after" Pseudo-element method the only one, which allows collapsing vertical margins? And shouldn't be this the preferable method? Imagine that you have two contiguous containers which are clearfixed. In the first one, you have an element:last-child with margin bottom. In the second one you have an element:first-child with margin-top. I think those margins should collapse but this is not the case, if you are using the "Beat That ClearFix" or Mirco clearfix method.

@zzzzBov 2016-02-02 14:40:29

@BeauSmith, I hope you don't mind; I've taken the liberty of adding information about Thierry Koblentz’ latest clearfix article to your answer. Please review it and make any corrections you see fit. I did my best to match the general tone and style of the rest of your answer.

@Ilya Streltsyn 2017-07-28 08:11:20

What is the point of setting the container display: inline-block; and then redefining it to block in the last example?

@Beau Smith 2017-07-28 08:17:33

@IlyaStreltsyn Follow the link for more info. You'll read that it's a Win/IE fix.

@Ilya Streltsyn 2017-07-28 08:28:45

@BeauSmith following the link, I see something different: they set inline-block for Mac IE (which ceased to exist more than a decade ago) and then return the block value for (old) Win IE only (via IE proprietary mechanism called Conditional Comments) along with classic IE zoom:1 hasLayout switch. So inline-block doesn't take part in Win IE fixing, and in your example it seems to be just ignored. Also, it's a bit strange to see caring about IE5- and not caring about IE8 (:: syntax) in the same code:)

@Beau Smith 2017-07-29 23:25:33

@IlyaStreltsyn - Thanks, much appreciated. I've updated the whole answer. Since this solution is aging, I decided to simply link to the solution rather than summarizing.

@Damien Golding 2017-08-17 11:45:56

A new display value seems to the job in one line.

display: flow-root;

From the w3 spec: "The element generates a block container box, and lays out its contents using flow layout. It always establishes a new block formatting context for its contents."

Information: https://www.w3.org/TR/css-display-3/#valdef-display-flow-root https://www.chromestatus.com/feature/5769454877147136

※As shown in the link above, support is currently limited so fallback support like below may be of use: https://github.com/fliptheweb/postcss-flow-root

@iono 2013-04-19 07:28:57

The new standard, as used by Inuit.css and Bourbon - two very widely used and well-maintained CSS/Sass frameworks:

.btcf:after {
    content:"";
    display:block;
    clear:both;
}

Notes

Keep in mind that clearfixes are essentially a hack for what flexbox layouts can now provide in a much smarter way. CSS floats were originally designed for inline content to flow around - like images in a long textual article - and not for grid layouts and the like. If your target browsers support flexbox, it's worth looking into.

This doesn't support IE7. You shouldn't be supporting IE7. Doing so continues to expose users to unfixed security exploits and makes life harder for all other web developers, as it reduces the pressure on users and organisations to switch to modern browsers.

This clearfix was announced and explained by Thierry Koblentz in July 2012. It sheds unnecessary weight from Nicolas Gallagher's 2011 micro-clearfix. In the process, it frees a pseudo-element for your own use. This has been updated to use display: block rather than display: table (again, credit to Thierry Koblentz).

@rafaelbiten 2013-07-12 02:20:32

I hope your answer gets more up votes on this as I totally agree with you. Again, it's 2013 and I truly believe this is the solution people should be using.

@Justin 2013-08-28 21:45:04

Agreed. theie7countdown.com Check your own analytics and hopefully see IE7 is not worth your time.

@iono 2013-09-05 07:39:49

@Justin agreed; your personal analytics will lay this out. I don't think that countdown site has been updated in a while, though - best to use caniuse's stats which put IE7 at 0.39% globally.

@iono 2013-11-29 09:45:30

Hopefully, hacks like the clearfix will soon be rendered unnecessary through use of flexbox, rather than floats, for layout.

@Kris Selbekk 2015-03-17 08:48:39

You can object to supporting IE7 as much as you want, but if there's a requirement from the business end to support these users (for different reasons - typically money), you're going to do it no matter how you feel on the issue

@iono 2015-03-18 08:21:51

@KrisSelbekk encouraging users to remain in an environment where they're exposed to known security risks for the sake of (likely very little) profit is unethical. You always have the option of rejecting the job, even though it would probably never need to come to that: in many situations you could make the case that your added development time spent supporting IE7 costs more than the income from a paltry IE7 user base.

@Kris Selbekk 2015-03-18 12:27:37

@iono - very true in most cases - not in all though. But the percentage of visits (profits) coming from IE7 users are less and less every day, so hopefully we can make the jump to at least IE8 or IE9 sometime this year :)

@Chris Calo 2012-03-29 19:54:41

What problems are we trying to solve?

There are two important considerations when floating stuff:

  1. Containing descendant floats. This means that the element in question makes itself tall enough to wrap all floating descendants. (They don't hang outside.)

    Floating content hanging outside its container

  2. Insulating descendants from outside floats. This means that descendants inside of an element should be able to use clear: both and have it not interact with floats outside the element.

    <code>clear: both</code> interacting with a float elsewhere in the DOM

Block formatting contexts

There's only one way to do both of these. And that is to establish a new block formatting context. Elements that establish a block formatting context are an insulated rectangle in which floats interact with each other. A block formatting context will always be tall enough to visually wrap its floating descendants, and no floats outside of a block formatting context may interact with elements inside. This two-way insulation is exactly what you want. In IE, this same concept is called hasLayout, which can be set via zoom: 1.

There are several ways to establish a block formatting context, but the solution I recommend is display: inline-block with width: 100%. (Of course, there are the usual caveats with using width: 100%, so use box-sizing: border-box or put padding, margin, and border on a different element.)

The most robust solution

Probably the most common application of floats is the two-column layout. (Can be extended to three columns.)

First the markup structure.

<div class="container">
  <div class="sidebar">
    sidebar<br/>sidebar<br/>sidebar
  </div>
  <div class="main">
    <div class="main-content">
      main content
      <span style="clear: both">
        main content that uses <code>clear: both</code>
      </span>
    </div>
  </div>
</div>

And now the CSS.

/* Should contain all floated and non-floated content, so it needs to
 * establish a new block formatting context without using overflow: hidden.
 */
.container {
  display: inline-block;
  width: 100%;
  zoom: 1; /* new block formatting context via hasLayout for IE 6/7 */
}

/* Fixed-width floated sidebar. */
.sidebar {
  float: left;
  width: 160px;
}

/* Needs to make space for the sidebar. */
.main {
  margin-left: 160px;
}

/* Establishes a new block formatting context to insulate descendants from
 * the floating sidebar. */
.main-content {
  display: inline-block;
  width: 100%;
  zoom: 1; /* new block formatting context via hasLayout for IE 6/7 */
}

Try it yourself

Go to JS Bin to play around with the code and see how this solution is built from the ground up.

Traditional clearfix methods considered harmful

The problem with the traditional clearfix solutions is that they use two different rendering concepts to achieve the same goal for IE and everyone else. In IE they use hasLayout to establish a new block formatting context, but for everyone else they use generated boxes (:after) with clear: both, which does not establish a new block formatting context. This means things won't behave the same in all situations. For an explanation of why this is bad, see Everything you Know about Clearfix is Wrong.

@Baumr 2013-01-07 20:02:39

What are "the usual caveats with using width: 100%"? Also, are you suggesting to use zoom: 1 in ¶1 of §2?

@Baumr 2013-01-07 20:09:05

Interesting answer, but what about overflow: hidden, what rendering concept does that invoke? And how can it be different to hasLayout?

@Baumr 2013-01-07 20:53:00

True, but if one avoids using position: absolute, then it's fine and will be part of the same rendering concept?

@Baumr 2013-01-07 21:56:39

I see. By rendering concept I meant if overflow: hidden enforces such a thing that differs to what hasLayout does?

@Baumr 2013-01-08 14:21:01

Thank you, so to confirm: the overflow: hidden and hasLayout are in the same block formatting context, while the others you suggested towards the end are different?

@Baumr 2013-01-08 15:01:41

So cases of hasLayout include some of the CSS declarations mentioned? Or are they all independent?

@Chris Calo 2013-01-08 15:14:48

Read more about hasLayout at stackoverflow.com/questions/1794350/what-is-haslayout. I think of it as synonymous with establishing a new block formatting context. Elements that do this are essentially responsible for the layout of all of their descendant elements. One result of this is that elements that establish a new block formatting context contain floated descendants and floats outside of the element don't interact with clear: left|right|both elements inside. (This is in the answer above.)

@David Seek 2018-12-15 01:27:40

this kept me busy for hours and your answer is the best of everything that i have been able to find in 1hour+

@Serge Stroobandt 2015-04-08 11:20:18

Unlike other clearfixes, here is an open-ended one without containers

Other clearfixes either require the floated element to be in a well marked off container or need an extra, semantically empty <div>. Conversely, clear separation of content and markup requires a strict CSS solution to this problem.

The mere fact that one needs to mark off the end of a float, does not allow for unattended CSS typesetting.

If the latter is your goal, the float should be left open for anything (paragraphs, ordered and unordered lists etc.) to wrap around it, until a "clearfix" is encountered. For example, the clearfix might be set by a new heading.

This is why I use the following clearfix with new headings:

h1 {
    clear: both;
    display: inline-block;
    width: 100%;
}

This solution gets used extensively on my website to solve the problem: The text next to a floated miniature is short and the top-margin of the next clearing object is not respected.

It also prevents any manual intervention when automatically generating PDFs from the site. Here is an example page.

@Eric 2016-03-10 09:25:46

My Favourite Method is to create a clearfix class in my css / scss document as below

.clearfix{
    clear:both
}

And then call it in my html document as shown below

<html>
  <div class="div-number-one">
    Some Content before the clearfix
  </div>

  <!-- Let's say we need to clearfix Here between these two divs --->
  <div class="clearfix"></div>

  <div class="div-number-two">
    Some more content after the clearfix
  </div>
</html>

@John Slegers 2014-01-07 19:02:52

I always use the micro-clearfix :

.cf:before,
.cf:after {
    content: " ";
    display: table;
}

.cf:after {
    clear: both;
}

/**
 * For IE 6/7 only
 */
.cf {
    *zoom: 1;
}

In Cascade Framework I even apply it by default on block level elements. IMO, applying it by default on block level elements gives block level elements more intuitive behavior than their traditonal behavior. It also made it a lot easier for me to add support for older browsers to Cascade Framework (which supports IE6-8 as well as modern browsers).

@draco 2009-08-27 13:19:40

Using overflow:hidden/auto and height for ie6 will suffice if the floating container has a parent element.

Either one of the #test could work, for the HTML stated below to clear floats.

#test {
  overflow:hidden; // or auto;
  _height:1%; forces hasLayout in IE6
}

<div id="test">
  <div style="floatLeft"></div>
  <div style="random"></div>
</div>

In cases when this refuses to work with ie6, just float the parent to clear float.

#test {
  float: left; // using float to clear float
  width: 99%;
}

Never really needed any other kind of clearing yet. Maybe it's the way I write my HTML.

@Starx 2011-07-29 09:22:38

I would like to study your way of writing HTML without clearing any elements. Could you post some links?

@jmu 2013-03-20 12:00:23

With LESS (http://lesscss.org/), one can create a handy clearfix helper:

.clearfix() {
  zoom: 1;
  &:before { 
    content: ''; 
    display: block; 
  }
  &:after { 
    content: ''; 
    display: table; 
    clear: both; 
  }
}

And then use it with problematic containers, for example:

<!-- HTML -->
<div id="container">
  <div id="content"></div>
  <div id="sidebar"></div>
</div>
/* LESS */
div#container {
  .clearfix();
}

@Vipul Vaghasiya 2013-03-08 10:13:38

#content{float:left;}
#sidebar{float:left;}
.clear{clear:both; display:block; height:0px; width:0px; overflow:hidden;}
<div id="container">
  <div id="content">text 1 </div>
  <div id="sidebar">text 2</div>
  <div class="clear"></div>
</div>

@fernandopasik 2014-05-05 18:46:16

With SASS, the clearfix is:

@mixin clearfix {
    &:before, &:after {
        content: '';
        display: table;
    }
    &:after {
        clear: both;
    }
    *zoom: 1;
}

and it's used like:

.container {
    @include clearfix;
}

if you want the new clearfix:

@mixin newclearfix {
    &:after {
        content:"";
        display:table;
        clear:both;
    }
}

@Tim Huynh 2011-06-19 19:42:55

Assuming you're using this HTML structure:

<div id="container">
  <div id="content">
  </div>
  <div id="sidebar">
  </div>
</div>

Here's the CSS that I would use:

div#container {
    overflow: hidden;    /* makes element contain floated child elements */
}

div#content, div#sidebar {
    float: left;
    display: inline;    /* preemptively fixes IE6 dobule-margin bug */
}

I use this set all the time and it works fine for me, even in IE6.

@Gaurang 2012-10-26 05:29:11

A clearfix is a way for an element to automatically clear after itself, so that you don't need to add additional markup.

.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}
.cleaner {
  clear: both;
}

Normally you would need to do something as follows:

<div style="float: left;">Sidebar</div>
<div class="cleaner"></div> <!-- Clear the float -->

With clearfix, you only need to

<div style="float: left;" class="clearfix">Sidebar</div>
<!-- No Clearing div! -->

@Jack Sleight 2009-02-10 11:20:54

The overflow property can be used to clear floats with no additional mark-up:

.container { overflow: hidden; }

This works for all browsers except IE6, where all you need to do is enable hasLayout (zoom being my preferred method):

.container { zoom: 1; }

http://www.quirksmode.org/css/clearing.html

@gtd 2009-08-19 19:19:41

overflow: hidden doesn't work in the PS3 browser. Not that most people need that to work, but it is the most significant thing blowing up my site in PS3 which we are trying to target for business reasons. Ugh.

@Simon East 2011-09-05 23:41:27

And it's a problem if you actually want certain content to hang outside of the container.

@Chris Calo 2012-03-29 18:14:53

overflow: hidden has a bad side effect of clipping content

@Tamlyn 2013-06-10 14:04:34

overflow:hidden has the effect of clipping content; it has the side effect of clearing the container ;-)

@Harry Robbins 2015-12-23 00:31:18

overflow:auto will also trigger a block formatting context, and it won't clip the content.

@paulslater19 2011-04-21 14:46:44

This is quite a tidy solution:

/* For modern browsers */
.cf:before,
.cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

/* For IE 6/7 (trigger hasLayout) */
.cf {
    zoom:1;
}

It's known to work in Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+

Including the :before selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This ensures that there is visual consistency with IE 6/7 when zoom:1 is applied.

From http://nicolasgallagher.com/micro-clearfix-hack/

@Simon East 2011-06-28 00:46:16

Yes, as of mid-2011, this is my favourite solution. It allows you to position objects outside the containing box if necessary (avoiding overflow: hidden).

@user1870829 2012-12-05 07:12:19

Clearfix from bootstrap:

.clearfix {
  *zoom: 1;
}

.clearfix:before,
.clearfix:after {
  display: table;
  line-height: 0;
  content: "";
}

.clearfix:after {
  clear: both;
}

@Eric 2015-09-28 15:16:34

Which version of bootstrap is this from?

@SimonSimCity 2009-01-20 15:50:12

I've found a bug in the official CLEARFIX-Method: The DOT doesn't have a font-size. And if you set the height = 0 and the first Element in your DOM-Tree has the class "clearfix" you'll allways have a margin at the bottom of the page of 12px :)

You have to fix it like this:

/* float clearing for everyone else */
.clearfix:after{
  clear: both;
  content: ".";
  display: block;
  height: 0;
  visibility: hidden;
  font-size: 0;
}

It's now part of the YAML-Layout ... Just take a look at it - it's very interesting! http://www.yaml.de/en/home.html

@Omar 2015-03-19 23:22:18

Given the huge amount of replies I was not gonna post. However, this method may help someone, as it did help me.

Stay way from floats whenever possible

It's worth to mention, I avoid floats like Ebola. There's many reasons and I am not alone; Read Rikudo answer about what is a clearfix and you'll see what I mean. In his own words: ...the use of floated elements for layout is getting more and more discouraged with the use of better alternatives...

There are other good (and sometimes better) options out there other than floats. As technology advances and improves, flexbox (and other methods) are going to be widely adopted and floats will become just a bad memory. Maybe a CSS4?


Float misbehavior and failed clears

First off, sometimes, you may think that you are safe from floats until your lifesaver is punctured and your html flow starts to sink:

In the codepen http://codepen.io/omarjuvera/pen/jEXBya below, the practice of clearing a float with <div classs="clear"></div> (or other element) is common but frown upon and anti-semantic.

<div class="floated">1st</div>
<div class="floated">2nd</div>
<div class="floated">3nd</div>
<div classs="clear"></div> <!-- Acts as a wall -->
<section>Below</section>

CSS

div {
    border: 1px solid #f00;
    width: 200px;
    height: 100px;
}

div.floated {
    float: left;
}

.clear {
    clear: both;
}
section {
    border: 1px solid #f0f;
}

However, just when you thought your float is sail worthy...boom! As the screen size becomes smaller and smaller you see weird behaviors in like the graphic below (Same http://codepen.io/omarjuvera/pen/jEXBya):

float bug sample 1

Why should you care? I am not sure of the exact figure but about 80% (or more) of the devices used are mobile devices with small screens. Desktop computers/laptops are no longer king.


It does not end there

This is not the only problem with floats. There are many, but in this example, some may say all you have to do is to place your floats in a container. But as you can see in the codepen and graphic, that is not the case. It apparently made things worst:

HTML

<div id="container" class="">
  <div class="floated">1st</div>
  <div class="floated">2nd</div>
  <div class="floated">3nd</div>
</div> <!-- /#conteiner -->
<div classs="clear"></div> <!-- Acts as a wall -->
<section>Below</section>

CSS

#container {
  min-height: 100px; /* To prevent it from collapsing */
  border: 1px solid #0f0;
}
.floated {
    float: left;
    border: 1px solid #f00;
    width: 200px;
    height: 100px;
}

.clear {
    clear: both;
}
section {
    border: 1px solid #f0f;
}

As for the result?

It's the *** same! float bug sample 2

Least you know, you'll start a CSS party, inviting all kinds of selectors and properties to the party; making a bigger mess of your CSS than what you started with. Just to fix your float.


CSS Clearfix to the rescue

This simple and very adaptable piece of CSS is a beauty and a "savior":

.clearfix:before, .clearfix:after { 
    content: "";
    display: table;
    clear: both;
    zoom: 1; /* ie 6/7 */
}

That's it! It really works without breaking semantics and did I mention it works?:

From the same sample...HTML

<div class="clearfix">
    <div class="floated">1st</div>
    <div class="floated">2nd</div>
    <div class="floated">3nd</div>
</div>
<section>Below</section>

CSS

div.floated {
    float: left;
    border: 1px solid #f00;
    width: 200px;
    height: 100px;
}
section {
        border: 4px solid #00f;
}


.clearfix:before, .clearfix:after { 
    content: "";
    display: table;
    clear: both;
    zoom: 1; /* ie 6/7 */
}

Now we no longer need <div classs="clear"></div> <!-- Acts as a wall --> and keep the semantic police happy. This is not the only benefit. This clearfix is responsive to any screen size without the use of @media in it's simplest form. In other words, it will keep your float container in check and preventing floodings. Lastly, it provides support for old browsers all in one small karate chop =)

Here's the clearfix again

.clearfix:before, .clearfix:after { 
    content: "";
    display: table;
    clear: both;
    zoom: 1; /* ie 6/7 */
}

@chestnut 2015-05-05 11:09:39

The reason why the element with clear class name not work is that your attribute class is wrong. What you wrote is classs, with an additional s.

@iamnotmaynard 2015-10-22 18:33:08

Your example does not demonstrate what you claim, even after correcting errors.

@Neil G 2011-08-18 02:12:14

I always float the main sections of my grid and apply clear: both; to the footer. That doesn't require an extra div or class.

@Simon East 2011-08-23 02:33:16

Neil, I guess the trouble comes when you want a border around both your columns (or a background colour/image), you need a wrapper section which needs the containing hack.

@Thierry Koblentz 2010-05-26 03:16:51

I'd float #content too, that way both columns contain floats. Also because it will allow you to clear elements inside #content without clearing the side bar.

Same thing with the wrapper, you'd need to make it a block formatting context to wrap the two columns.

This article mentions a few triggers you can use: block formatting contexts.

@Eric the Red 2010-09-27 15:16:11

I recommend using the following, which is taken from http://html5boilerplate.com/

/* >> The Magnificent CLEARFIX << */
.clearfix:after { 
  content: "."; 
  display: block; 
  height: 0; 
  clear: both; 
  visibility: hidden; 
}
.clearfix { 
  display: inline-block;  
}
* html .clearfix {  
  height: 1%;  
} /* Hides from IE-mac \*/
.clearfix {  
  display: block;  
}

@Ilya Streltsyn 2013-07-31 16:08:36

Who remembers IE-mac now? Why make things so complicated because of problems that are no more relevant?

@John Xiao 2012-09-02 10:22:32

I have tried all these solutions, a big margin will be added to <html> element automatically when I use the code below:

.clearfix:after {   
    visibility: hidden;   
    display: block;   
    content: ".";   
    clear: both;   
    height: 0;
}

Finally, I solved the margin problem by adding font-size: 0; to the above CSS.

@Forty 2016-07-21 17:12:37

That's because you're adding a line with ., just use content: ""

@Hakan 2011-04-01 22:50:58

You could also put this in your CSS:

.cb:after{
  visibility: hidden;
  display: block;
  content: ".";
  clear: both;
  height: 0;
}

*:first-child+html .cb{zoom: 1} /* for IE7 */

And add class "cb" to your parent div:

<div id="container" class="cb">

You will not need to add anything else to your original code...

@Phpascal 2011-05-20 12:52:47

Why just trying to use css hack to do what 1 line of HTML do the job. And why not to use semantic html tu put break to return to the line?

Fo me is realy better to use :

<br style="clear:both" />

And if you don't want any style in your html you just have to use class for your break and put .clear { clear:both; } in your CSS.

Advantage of this:

  • Semantic use of html for return to the line
  • If no CSS load it will be working
  • No need extra CSS code and Hack
  • no need to simulate the br with CSS, it's already exist in HTML

@Salman von Abbas 2011-02-21 13:03:15

I just use :-

.clear:after{
  clear: both;
  content: "";
  display: block;
}

Works best and compatible with IE8+ :)

@superluminary 2013-04-16 09:27:12

Won't work in IE7 as it has no support for CSS pseudoelements.

@Justin 2013-08-12 19:54:37

... That is why he said "compatible with IE8+." Most websites don't need to support IE7 anymore, it's usage is less than 1% worldwide. theie7countdown.com

@duggi 2010-07-07 16:39:45

honestly; all solutions seem to be a hack to fix a rendering bug ... am i wrong?

i've found <br clear="all" /> to be the easiest, simplest. seeing class="clearfix" everywhere can't stroke the sensibilities of someone who objects to extraneous markeup elements, can it? you're just painting the problem on a different canvas.

i also use the display: hidden solution, which is great and requires no extra class declarations or html markup ... but sometimes you need the elements to overflow the container, for eg. pretty ribbons and sashes

@ajbeaven 2011-05-10 23:47:35

overflow: hidden I think you mean

@Damon 2011-09-29 13:26:49

Some recommend using class called group which makes things more semantic. I'm frankly not sure why this hasn't caught on

@duggi 2011-10-03 23:41:59

im totally retracting this position. i just use clearfix now. but on very common containers, i 'bake' it into the css to cut down on class attribute pollution. also, naming it 'group' seems nice. less chars to type as well

@Torkel 2008-10-17 08:34:53

Have you tried this:

<div style="clear:both;"/>

I haven't had any problems with this method.

@Sam Murray-Sutton 2009-02-09 11:55:16

I think the point is we're trying to avoid both extra markup and inline styles with this solution. It depends which compromise your happiest with I suppose

@zznq 2010-09-02 21:27:32

The problem with this method is that in IE browsers the div has a height, so your spacing will be off. That is why the css methods set height and font-size.

@Simon_Weaver 2013-03-12 04:02:30

you need to say <div style="clear:both"></div> with a proper closing tag to be propertly XHTML compliant. I've had jQuery issues when not doing this

@Ilya Streltsyn 2013-07-31 16:05:31

Ironically, "supposed-to-be-self-closed" <div/> is X(HT)ML compliant, but isn't HTML compatible, so for documents served as text/html all browsers will treat it as unclosed tag. There is no such thing like self-closing tags for text/html documents, regardless of the doctype, unfortunately.

Related Questions

Sponsored Content

10 Answered Questions

[SOLVED] What is a clearfix?

44 Answered Questions

[SOLVED] How can I transition height: 0; to height: auto; using CSS?

33 Answered Questions

[SOLVED] How can I make Bootstrap columns all the same height?

6 Answered Questions

[SOLVED] IE7 HTML/CSS margin-bottom bug

17 Answered Questions

[SOLVED] What is the difference between visibility:hidden and display:none?

  • 2008-09-25 12:37:47
  • Chris Noe
  • 533324 View
  • 1107 Score
  • 17 Answer
  • Tags:   css visibility

22 Answered Questions

[SOLVED] What is the best way to conditionally apply a class?

  • 2011-10-17 10:49:52
  • respectTheCode
  • 756888 View
  • 1167 Score
  • 22 Answer
  • Tags:   css angularjs

3 Answered Questions

[SOLVED] What does the clearfix class do in css?

  • 2012-03-03 04:46:30
  • Gnijuohz
  • 157240 View
  • 86 Score
  • 3 Answer
  • Tags:   html css clearfix

3 Answered Questions

[SOLVED] clear-fix not working (chrome)

  • 2013-06-19 13:32:38
  • user2273652
  • 228 View
  • 3 Score
  • 3 Answer
  • Tags:   css css-float clear

1 Answered Questions

Can't get 100% height to work (read most posts here and tried for 1+ hours)

  • 2013-01-10 22:13:00
  • Charles Ingalls
  • 205 View
  • 0 Score
  • 1 Answer
  • Tags:   height css

1 Answered Questions

Sponsored Content