What is a clearfix? - html

Recently I was looking through some website's code, and saw that every <div> had a class clearfix.
After a quick Google search, I learned that it is for IE6 sometimes, but what actually is a clearfix?
Could you provide some examples of a layout with a clearfix, compared to a layout without a clearfix?

If you don't need to support IE9 or lower, you can use flexbox freely, and don't need to use floated layouts.
It's worth noting that today, the use of floated elements for layout is getting more and more discouraged with the use of better alternatives.
display: inline-block - Better
Flexbox - Best (but limited browser support)
Flexbox is supported from Firefox 18, Chrome 21, Opera 12.10, and Internet Explorer 10, Safari 6.1 (including Mobile Safari) and Android's default browser 4.4.
For a detailed browser list see: https://caniuse.com/flexbox.
(Perhaps once its position is established completely, it may be the absolutely recommended way of laying out elements.)
A clearfix is a way for an element to automatically clear its child elements, so that you don't need to add additional markup. It's generally used in float layouts where elements are floated to be stacked horizontally.
The clearfix is a way to combat the zero-height container problem for floated elements
A clearfix is performed as follows:
.clearfix::after {
content: " "; /* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}
Or, if you don't require IE<8 support, the following is fine too:
.clearfix::after {
content: "";
display: table;
clear: both;
}
Normally you would need to do something as follows:
<div>
<div style="float: left;">Sidebar</div>
<div style="clear: both;"></div> <!-- Clear the float -->
</div>
With clearfix, you only need the following:
<div class="clearfix">
<div style="float: left;" class="clearfix">Sidebar</div>
<!-- No Clearing div! -->
</div>
Read about it in this article - by Chris Coyer # CSS-Tricks

The other answers are correct. But I want to add that it is a relic of the time when people were first learning CSS, and abused float to do all their layout. float is meant to do stuff like float images next to long runs of text, but lots of people used it as their primary layout mechanism. Since it wasn't really meant for that, you need hacks like "clearfix" to make it work.
These days display: inline-block is a solid alternative (except for IE6 and IE7), although more modern browsers are coming with even more useful layout mechanisms under names like flexbox, grid layout, etc.

The clearfix allows a container to wrap its floated children. Without a clearfix or equivalent styling, a container does not wrap around its floated children and collapses, just as if its floated children were positioned absolutely.
There are several versions of the clearfix, with Nicolas Gallagher and Thierry Koblentz as key authors.
If you want support for older browsers, it's best to use this clearfix :
.clearfix:before, .clearfix:after {
content: "";
display: table;
}
.clearfix:after {
clear: both;
}
.clearfix {
*zoom: 1;
}
In SCSS, you could use the following technique :
%clearfix {
&:before, &:after {
content:" ";
display:table;
}
&:after {
clear:both;
}
& {
*zoom:1;
}
}
#clearfixedelement {
#extend %clearfix;
}
If you don't care about supporting older browsers, there's a shorter version :
.clearfix:after {
content:"";
display:table;
clear:both;
}

To offer an update on the situation on Q2 of 2017.
A new CSS3 display property is available in Firefox 53, Chrome 58 and Opera 45.
.clearfix {
display: flow-root;
}
Check the availability for any browser here: http://caniuse.com/#feat=flow-root
The element (with a display property set to flow-root) generates a block container box, and lays out its contents using flow layout. It always establishes a new block formatting context for its contents.
Meaning that if you use a parent div containing one or several floating children, this property is going to ensure the parent encloses all of its children. Without any need for a clearfix hack. On any children, nor even a last dummy element (if you were using the clearfix variant with :before on the last children).
.container {
display: flow-root;
background-color: Gainsboro;
}
.item {
border: 1px solid Black;
float: left;
}
.item1 {
height: 120px;
width: 120px;
}
.item2 {
height: 80px;
width: 140px;
float: right;
}
.item3 {
height: 160px;
width: 110px;
}
<div class="container">
This container box encloses all of its floating children.
<div class="item item1">Floating box 1</div>
<div class="item item2">Floating box 2</div>
<div class="item item3">Floating box 3</div>
</div>

Simply put, clearfix is a hack.
It is one of those ugly things that we all just have to live with as it is really the only reasonable way of ensuring floated child elements don't overflow their parents. There are other layout schemes out there but floating is too commonplace in web design/development today to ignore the value of the clearfix hack.
I personally lean towards the Micro Clearfix solution (Nicolas Gallagher)
.container:before,
.container:after {
content:"";
display:table;
}
.container:after {
clear:both;
}
.container {
zoom:1; /* For IE 6/7 (trigger hasLayout) */
}
reference

A technique commonly used in CSS float-based layouts is assigning a handful of CSS properties to an element which you know will contain floating elements. The technique, which is commonly implemented using a class definition called clearfix, (usually) implements the following CSS behaviors:
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
zoom: 1
}
The purpose of these combined behaviors is to create a container :after the active element containing a single '.' marked as hidden which will clear all preexisting floats and effectively reset the the page for the next piece of content.

I tried out the accepted answer but I still had a problem with the content alignment. Adding a ":before" selector as shown below fixed the issue:
// LESS HELPER
.clearfix()
{
&:after, &:before{
content: " "; /* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}
}
LESS above will compile to CSS below:
clearfix:after,
clearfix:before {
content: " ";
/* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}

The other (and perhaps simplest) option for acheiving a clearfix is to use overflow:hidden; on the containing element. For example
.parent {
background: red;
overflow: hidden;
}
.segment-a {
float: left;
}
.segment-b {
float: right;
}
<div class="parent">
<div class="segment-a">
Float left
</div>
<div class="segment-b">
Float right
</div>
</div>
Of course this can only be used in instances where you never wish the content to overflow.

What is Clearfix?
A way for an element to clear its child elements automatically without any additional markup.
Working with properties: CSS clearfix is used to fix the overflow elements from the desired element. This can be worked with 3 properties:
Overflow Property
Height Property
Float Property
This all 3 CSS properties are used for fixing the overflow elements.
Why ClearFix?
To avoid adding unnecessary markup, an element can automatically clear or fix its elements using a clearfix.
It is employed in float layouts where elements are floated to form a horizontal stack.
When Clearfix?
When two or more floating items are placed next to one another.
When items are positioned in this fashion, the parent container has a height of 0, which can easily mess up a layout. The problem is inconsistent among browsers, which makes matters more difficult. To address all of that, the clearfix was created.
Like this:
Example(for your understanding):
<head>
<style>
div {
border: 3px solid #4CAF50;
padding: 5px;
}
.img1 {
float: right;
}
.img2 {
float: right;
}
.clearfix {
overflow: auto;
}
</style>
</head>
<body>
<h2>Without Clearfix</h2>
<p>This image is floated to the right. It is also taller than the element containing it, so it overflows outside of its container:</p>
<div>
<img class="img1" src="pineapple.jpg" alt="Pineapple" width="170" height="170">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet...
</div>
<h2 style="clear:right">With Clearfix</h2>
<p>We can fix this by adding a clearfix class with overflow: auto; to the containing element:</p>
<div class="clearfix">
<img class="img2" src="pineapple.jpg" alt="Pineapple" width="170" height="170">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet...
</div>
</body>
Output of above code:
Is Clearfix becoming obselete?
Almost 15 years after it was first proposed and with the updates in 2007 and 2013, today the clearfix is losing relevance because today CSS Grid and Flexbox are filling in the gaps for advanced layout on the web.
Hope it helps.

Here is a different method same thing but a little different
the difference is the content dot which is replaced with a \00A0 == whitespace
More on this http://www.jqui.net/tips-tricks/css-clearfix/
.clearfix:after { content: "\00A0"; display: block; clear: both; visibility: hidden; line-height: 0; height: 0;}
.clearfix{ display: inline-block;}
html[xmlns] .clearfix { display: block;}
* html .clearfix{ height: 1%;}
.clearfix {display: block}
Here is a compact version of it...
.clearfix:after { content: "\00A0"; display: block; clear: both; visibility: hidden; line-height: 0; height: 0;width:0;font-size: 0px}.clearfix{ display: inline-block;}html[xmlns] .clearfix { display: block;}* html .clearfix{ height: 1%;}.clearfix {display: block}

Related

Why isn't the background colour showing up in my divs? [duplicate]

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?
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:
css flexbox
css grid
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.
What problems are we trying to solve?
There are two important considerations when floating stuff:
Containing descendant floats. This means that the element in question makes itself tall enough to wrap all floating descendants. (They don't hang outside.)
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.
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.
The newest 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 easier and 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. Unless you're specifically targeting old (not Edge) Internet Explorer, your target browsers support flexbox, so it's worth the time to learn.
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 safer 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).
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;
}
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
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
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/
Clearfix from bootstrap:
.clearfix {
*zoom: 1;
}
.clearfix:before,
.clearfix:after {
display: table;
line-height: 0;
content: "";
}
.clearfix:after {
clear: both;
}
I just use :-
.clear:after{
clear: both;
content: "";
display: block;
}
Works best and compatible with IE8+ :)
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 are 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):
Why should you care?
Roughly, 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!
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 */
}
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.
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
.clearFix:after {
content: "";
display: table;
clear: both;
}
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
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;
}
}
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();
}
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.
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.
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.
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! -->
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
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.
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.
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).
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...
#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>
Have you tried this:
<div style="clear:both;"/>
I haven't had any problems with this method.
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>
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.

<div> with <span> float:left height is set to 0px [duplicate]

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?
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:
css flexbox
css grid
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.
What problems are we trying to solve?
There are two important considerations when floating stuff:
Containing descendant floats. This means that the element in question makes itself tall enough to wrap all floating descendants. (They don't hang outside.)
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.
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.
The newest 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 easier and 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. Unless you're specifically targeting old (not Edge) Internet Explorer, your target browsers support flexbox, so it's worth the time to learn.
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 safer 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).
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;
}
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
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
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/
Clearfix from bootstrap:
.clearfix {
*zoom: 1;
}
.clearfix:before,
.clearfix:after {
display: table;
line-height: 0;
content: "";
}
.clearfix:after {
clear: both;
}
I just use :-
.clear:after{
clear: both;
content: "";
display: block;
}
Works best and compatible with IE8+ :)
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 are 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):
Why should you care?
Roughly, 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!
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 */
}
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.
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
.clearFix:after {
content: "";
display: table;
clear: both;
}
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
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;
}
}
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();
}
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.
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.
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.
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! -->
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
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.
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.
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).
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...
#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>
Have you tried this:
<div style="clear:both;"/>
I haven't had any problems with this method.
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>
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.

Cant figure out why the background color on my main element won't change [duplicate]

Recently I was looking through some website's code, and saw that every <div> had a class clearfix.
After a quick Google search, I learned that it is for IE6 sometimes, but what actually is a clearfix?
Could you provide some examples of a layout with a clearfix, compared to a layout without a clearfix?
If you don't need to support IE9 or lower, you can use flexbox freely, and don't need to use floated layouts.
It's worth noting that today, the use of floated elements for layout is getting more and more discouraged with the use of better alternatives.
display: inline-block - Better
Flexbox - Best (but limited browser support)
Flexbox is supported from Firefox 18, Chrome 21, Opera 12.10, and Internet Explorer 10, Safari 6.1 (including Mobile Safari) and Android's default browser 4.4.
For a detailed browser list see: https://caniuse.com/flexbox.
(Perhaps once its position is established completely, it may be the absolutely recommended way of laying out elements.)
A clearfix is a way for an element to automatically clear its child elements, so that you don't need to add additional markup. It's generally used in float layouts where elements are floated to be stacked horizontally.
The clearfix is a way to combat the zero-height container problem for floated elements
A clearfix is performed as follows:
.clearfix::after {
content: " "; /* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}
Or, if you don't require IE<8 support, the following is fine too:
.clearfix::after {
content: "";
display: table;
clear: both;
}
Normally you would need to do something as follows:
<div>
<div style="float: left;">Sidebar</div>
<div style="clear: both;"></div> <!-- Clear the float -->
</div>
With clearfix, you only need the following:
<div class="clearfix">
<div style="float: left;" class="clearfix">Sidebar</div>
<!-- No Clearing div! -->
</div>
Read about it in this article - by Chris Coyer # CSS-Tricks
The other answers are correct. But I want to add that it is a relic of the time when people were first learning CSS, and abused float to do all their layout. float is meant to do stuff like float images next to long runs of text, but lots of people used it as their primary layout mechanism. Since it wasn't really meant for that, you need hacks like "clearfix" to make it work.
These days display: inline-block is a solid alternative (except for IE6 and IE7), although more modern browsers are coming with even more useful layout mechanisms under names like flexbox, grid layout, etc.
The clearfix allows a container to wrap its floated children. Without a clearfix or equivalent styling, a container does not wrap around its floated children and collapses, just as if its floated children were positioned absolutely.
There are several versions of the clearfix, with Nicolas Gallagher and Thierry Koblentz as key authors.
If you want support for older browsers, it's best to use this clearfix :
.clearfix:before, .clearfix:after {
content: "";
display: table;
}
.clearfix:after {
clear: both;
}
.clearfix {
*zoom: 1;
}
In SCSS, you could use the following technique :
%clearfix {
&:before, &:after {
content:" ";
display:table;
}
&:after {
clear:both;
}
& {
*zoom:1;
}
}
#clearfixedelement {
#extend %clearfix;
}
If you don't care about supporting older browsers, there's a shorter version :
.clearfix:after {
content:"";
display:table;
clear:both;
}
To offer an update on the situation on Q2 of 2017.
A new CSS3 display property is available in Firefox 53, Chrome 58 and Opera 45.
.clearfix {
display: flow-root;
}
Check the availability for any browser here: http://caniuse.com/#feat=flow-root
The element (with a display property set to flow-root) generates a block container box, and lays out its contents using flow layout. It always establishes a new block formatting context for its contents.
Meaning that if you use a parent div containing one or several floating children, this property is going to ensure the parent encloses all of its children. Without any need for a clearfix hack. On any children, nor even a last dummy element (if you were using the clearfix variant with :before on the last children).
.container {
display: flow-root;
background-color: Gainsboro;
}
.item {
border: 1px solid Black;
float: left;
}
.item1 {
height: 120px;
width: 120px;
}
.item2 {
height: 80px;
width: 140px;
float: right;
}
.item3 {
height: 160px;
width: 110px;
}
<div class="container">
This container box encloses all of its floating children.
<div class="item item1">Floating box 1</div>
<div class="item item2">Floating box 2</div>
<div class="item item3">Floating box 3</div>
</div>
Simply put, clearfix is a hack.
It is one of those ugly things that we all just have to live with as it is really the only reasonable way of ensuring floated child elements don't overflow their parents. There are other layout schemes out there but floating is too commonplace in web design/development today to ignore the value of the clearfix hack.
I personally lean towards the Micro Clearfix solution (Nicolas Gallagher)
.container:before,
.container:after {
content:"";
display:table;
}
.container:after {
clear:both;
}
.container {
zoom:1; /* For IE 6/7 (trigger hasLayout) */
}
reference
A technique commonly used in CSS float-based layouts is assigning a handful of CSS properties to an element which you know will contain floating elements. The technique, which is commonly implemented using a class definition called clearfix, (usually) implements the following CSS behaviors:
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
zoom: 1
}
The purpose of these combined behaviors is to create a container :after the active element containing a single '.' marked as hidden which will clear all preexisting floats and effectively reset the the page for the next piece of content.
I tried out the accepted answer but I still had a problem with the content alignment. Adding a ":before" selector as shown below fixed the issue:
// LESS HELPER
.clearfix()
{
&:after, &:before{
content: " "; /* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}
}
LESS above will compile to CSS below:
clearfix:after,
clearfix:before {
content: " ";
/* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}
The other (and perhaps simplest) option for acheiving a clearfix is to use overflow:hidden; on the containing element. For example
.parent {
background: red;
overflow: hidden;
}
.segment-a {
float: left;
}
.segment-b {
float: right;
}
<div class="parent">
<div class="segment-a">
Float left
</div>
<div class="segment-b">
Float right
</div>
</div>
Of course this can only be used in instances where you never wish the content to overflow.
What is Clearfix?
A way for an element to clear its child elements automatically without any additional markup.
Working with properties: CSS clearfix is used to fix the overflow elements from the desired element. This can be worked with 3 properties:
Overflow Property
Height Property
Float Property
This all 3 CSS properties are used for fixing the overflow elements.
Why ClearFix?
To avoid adding unnecessary markup, an element can automatically clear or fix its elements using a clearfix.
It is employed in float layouts where elements are floated to form a horizontal stack.
When Clearfix?
When two or more floating items are placed next to one another.
When items are positioned in this fashion, the parent container has a height of 0, which can easily mess up a layout. The problem is inconsistent among browsers, which makes matters more difficult. To address all of that, the clearfix was created.
Like this:
Example(for your understanding):
<head>
<style>
div {
border: 3px solid #4CAF50;
padding: 5px;
}
.img1 {
float: right;
}
.img2 {
float: right;
}
.clearfix {
overflow: auto;
}
</style>
</head>
<body>
<h2>Without Clearfix</h2>
<p>This image is floated to the right. It is also taller than the element containing it, so it overflows outside of its container:</p>
<div>
<img class="img1" src="pineapple.jpg" alt="Pineapple" width="170" height="170">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet...
</div>
<h2 style="clear:right">With Clearfix</h2>
<p>We can fix this by adding a clearfix class with overflow: auto; to the containing element:</p>
<div class="clearfix">
<img class="img2" src="pineapple.jpg" alt="Pineapple" width="170" height="170">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet...
</div>
</body>
Output of above code:
Is Clearfix becoming obselete?
Almost 15 years after it was first proposed and with the updates in 2007 and 2013, today the clearfix is losing relevance because today CSS Grid and Flexbox are filling in the gaps for advanced layout on the web.
Hope it helps.
Here is a different method same thing but a little different
the difference is the content dot which is replaced with a \00A0 == whitespace
More on this http://www.jqui.net/tips-tricks/css-clearfix/
.clearfix:after { content: "\00A0"; display: block; clear: both; visibility: hidden; line-height: 0; height: 0;}
.clearfix{ display: inline-block;}
html[xmlns] .clearfix { display: block;}
* html .clearfix{ height: 1%;}
.clearfix {display: block}
Here is a compact version of it...
.clearfix:after { content: "\00A0"; display: block; clear: both; visibility: hidden; line-height: 0; height: 0;width:0;font-size: 0px}.clearfix{ display: inline-block;}html[xmlns] .clearfix { display: block;}* html .clearfix{ height: 1%;}.clearfix {display: block}

Span style float:left is breaking div block [duplicate]

This question already has answers here:
Floating elements within a div, floats outside of div. Why?
(11 answers)
Closed 7 years ago.
I'm working on maintaining a bit of code that's out of whack at the moment. Basically, we have a <div> tag with it's own style settings, and we have multiple logic tags that will display different <span> tags, which will hold different bits of data.
What I'm seeing is that when I'm using a <span> tag with a style setting float: left; this is causing the <div> tag's color box to not wrap around the <span>.
Here's a sample of the code:
<div id="testData" style="padding:4px; width: 100%; border: 1px solid #999; background: #d1d1d1; text-align:right;">
<span style="padding: 3px 1 1 1; float:left;">
TestData: Float Left
</span>
</div>
I need this span tag to go left, due to requirements. Was wondering what my options are for this to work?
Original jsFiddle
Add overflow:auto to the parent div:
#testData {
overflow:auto;
}
jsFiddle example
Other way is to make use of clear: both
#testData:after {
clear: both;
display: block;
content: "";
}
Fiddle
Other solutions:
Using overflow: hidden
#testData {
overflow: hidden;
}
Or making a dummy element <div class="clearBoth"></div>
HTML
<div id="testData" style="padding:4px; width: 100%; border: 1px solid #999; background: #d1d1d1; text-align:right;">
<span style="padding: 3px 1 1 1; float:left;">
TestData: Float Left
</span>
<div class="clearBoth"></div>
</div>
CSS
.clearBoth {
clear: both;
}
http://jsfiddle.net/gLfw5wc7/3/
#testData {
padding:4px;
width: 100%;
border: 1px solid #999;
background: #d1d1d1;
text-align:right;
}
#testData:after {
content:"";
clear: both;
display: table;
}
#testData > span {
padding: 3px 1px 1px;
float:left;
}
This is known as a clearfix. When floating an element, it gets out "the flow" of the document. This also means that its width and height aren't taken into account by the parent. That's why #testData seems to collapse: it thinks it doesn't have content. To fix this there are some options. The easiest is to use overflow, however, that's bad practice imo. In this particular case it works, but in some other cases you won't be able to use it because content that overflows the parent will either be hidden (overflow: hidden) or a scrollbar will appear (overflow: auto).
The most common and proper solution is to use a pseudo element to fix this. :after is such a pseudo element (see this question for :after vs ::after). Basically, a pseudo element can create an element in CSS that is not visible in HTML.
Every time you use float, you'll be needing a clearfix. Therefore it's useful to create a .clear class which you can apply to every element that needs to clear floats. It would look like this.
HTML
<div id="testData" class="clear">
<span>
TestData: Float Left
</span>
</div>
CSS
.clear:after {
content:"";
clear: both;
display: table;
}
Now you can add class="clear" to every element that needs to be cleared. If you are into SASS, you might find this answer helpful but considering you are new to HTML, I'd suggest sticking to HTML and CSS first.

vertical alignment and floats

I'm sorry if my question seems stupid, but I spent too much time on this. I have a div display block containing two span, one on the right and the other one on the left.
<div class="user-bar">
<span class="username">Martin GOYOT</span>
<span class="user-options"><input type="button" class="disconnect" value="déconnexion"/></span>
</div>
I tried two thing to get them vertical aligned: First one, getting these two floats, but the problem is that I can clearly see that they are out of flow (normal) and thereby, if I apply a background, to the container, it doesn't cover them:
http://jsfiddle.net/M7Ffd/1/
Second solution, let the first in the flow and put the second one as a float, but the result is that I can't find out how to vertically aligning them:
http://jsfiddle.net/M7Ffd/2/ (be careful of the button, it is not really vertically aligned even if it looks like)
So, the question is: what is the best solution, and, how to fix at least one of these two misbehaviour.
thanks, and sorry, I'm a css newbie.
Vertical alignment is a hard issue. And floating seems to be everyone's first goto solution for everything. Avoid the gotos, how about using
position: absolute;
right: 0;
http://jsfiddle.net/M7Ffd/3/
Is this what you want? fiddle here
.user-bar {
padding: 0.5em;
margin: 0 1em 1em 1em;
background-color: green;
font-weight: bold;
font-size: 1.25em;
height:30px;
min-width:300px;
}
.user-options {
display: inline-block;
background-color: #CCC;
float: right;
}
.username {
float: left;
background: yellowgreen;
}
​
Setting the minimum width and giving height solves the alignment + Background solution.
Use the clearfix hack on the parent element of the 2 floated children to resolve your issue.
.clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; overflow: hidden; }
.clearfix:after { clear: both; }
.clearfix { zoom: 1; }
I updated your fiddle to show you it http://jsfiddle.net/M7Ffd/5/