Saturday, June 19, 2010

Clearing Floats The Old Fashioned Way

When a float is contained within a container box that has a visible border or background, that float does not automatically force the container's bottom edge down as the float is made taller. Instead the float is ignored by the container and will hang down out of the container bottom like a flag. Those familiar only with Explorer for Windows may scratch their heads and say "That's not right!" True, IE/Win does enclose a float within a container 'automatically', but only if the container element happens to possess the MS-only quality called hasLayout.

This float-enclosing behavior in IE can also be 'toggled' off again just by hovering of links within the container, if that hovering alters either the link background or one of several other CSS properties. Quite a mess, and we'll cover it farther along in the article, in the "Toggle Trouble" section.

The W3C suggests placing a "cleared" element last in the container box, which is then recognized by the container height, forcing the container to enclose the float above that cleared element too. It's described more fully our article Float: The Theory:

“..let's say you give that following box the clear property, {clear: both;} . What this does is extend the margin on the top of the cleared box, pushing it down until it "clears" the bottom of the float. In other words, the top margin on the cleared box (no matter what it may have been set to), is increased by the browser, to whatever length is necessary to keep the cleared box below the float.”

So in effect, such a cleared box cannot be at the same horizontal level as a preceding float. It must appear just below that level. The image shows how this might look, with a red border representing the container element:



The standard method of making an outer container appear to "enclose" a nested float is to place a complete "cleared" element last in the container, which has the effect of 'dragging' the lower edge of the containing box lower than the float. Thus the float appears to be enclosed within the container even tho it really isn't. The code for a cleared box usually looks something like this:

<div> <!-- float container -->

<div style="float:left; width:30%;"><p>Some content</p></div>

<p>Text not inside the float</p>

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

</div>

Since that div is not floated, the container must recognize it and enclose it, and because of that top margin (added by the browser because of the "clear" property), the div "pulls" the bottom edge of the container down below the bottom edge of the float.
Problems With The Method

First and foremost, this clearing method is not at all intuitive, requiring an extra element be added to the markup. One of the major premises of CSS is that it helps reduce the bloated HTML markup found it the average site these days. So having to re-bloat the markup just so floats can be kept within their containers is not an ideal arrangement.

Besides that, some browsers can have trouble with certain kinds of clearing elements in some situations. Mozilla is particularly sensitive to clearing problems.

Up 'til now there was no other way to do this, but no more! Thanks to the efforts of Tony Aslett, creator and operator of csscreator.com, we can now use advanced CSS to "clear" a float container in non-IE browsers and just let IE keep wrongly clearing itself. The upshot is that we now have the option to avoid adding that pesky clearing element to the HTML markup. Woohoo!

"Clearing", 21st Century Style

In the new method, no clearing element is used. This does not affect IE/Win which simply keeps enclosing the float as always (assuming the container has a stated dimension), but non-IE browsers will need a substitute for that element. Here's how it's done.

Using :after

This CSS 2 property allows extra content to be added at the end of an element via the CSS. That means no actual markup is needed in the HTML. The content is specified from within the CSS stylesheet, and appears in the page as would a real HTML element that had been inserted following all the normal content of the target element. Such :after generated content cannot receive some CSS properties, including 'position', 'float', list properties, and table properties. However, the 'clear' property is allowed. Do you see where we are going here?

Imagine that we use :after to insert a simple character like a 'period', and then give that generated element {clear: both;} . That's all you really need to do the job, but no one wants a line space messing up the end of their clean container box, so we also use {height: 0;} and {visibility: hidden;} to keep our period from showing.

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

Notice that {display: block;} is also applied to the :after element, because if it isn't then that element defaults to "inline", and cannot receive the "clear" property. Also, Tony's method originally used "overflow: hidden;" to hide the period, but sadly the latest FireFox versions will display the period if this is done.
But what about IE?

Since IE7 does not support the :after pseudoclass yet, we must rely on the same"auto-clearing" effect used for IE6, and that behavior happens when the float-containing element gets hasLayout applied to it. A simple declaration of "zoom: 1;" will perform this trick in IE5.5 and up, but it's proprietary and needs to be hidden in order to validate.

As a side benefit, hasLayout on float-enclosing elements also prevents several other major IE/Win float bugs. However, should this container box be placed following a previous external float, the IE height fix will trigger Microsoft's proprietary and illegal Float Model, so watch out for that, okay?
Toggle Trouble

It so happens that IE has, well, a little problem with this auto-enclosing behavior. You saw that coming, didn't you. Yes, IE bugs come in big bunches. This one results when that container element has links inside, following the float. When this happens and certain links are hovered, the auto-enclosing behavior is toggled or "switched off", causing the lower edge of the container box to suddenly jump up to the bottom of the non-floated content. Hovering other links restores the behavior. This interesting effect is of course called the IE/Win Guillotine Bug Those of you viewing in IE/Win may play around with the following live demos, and for a more complete explanation see the IE/Win Guillotine Bug demo page .

The toggling only occurs when a:hover is used to change the link background or many other styling changes, such as padding, margin, or any font styling on the link. Strangely, having the text color change on hover does not toggle the bug.

The containers are grey with green borders, and the floats are dark brown with yellow borders. Notice how the third and fourth links ouside the floats toggle the Guillotine Bug, and the first two un-toggle it. This seems to be related to the actual text lines themselves, so any links after the first two lines will toggle the effect. Links in the float will all un-toggle the effect. Just more weird IE bug behaviors, folks, nothing "unusual".
Screenshot

The second demo has been "fixed" by placing those links in a paragraph, which then gets the zoom fix applied to it. Any block element will do just as well here. Yes, this means another element is needed, but unlike a clearing div, this paragraph is a "semantic" element. Text content really ought to be wrapped in semantic containers anyway, and since we forward-thinking coders always have our content thusly contained, it's easy to apply the same .clearfix class to one more element.
A Word About Floats In Floats

Observant readers will have noticed that the above demos have "enclosed" floats, even in Opera 7 and Mozilla! This is because the demos themselves are floats, and all modern browsers (including IE, luckily) always let floats enclose other floats. Of course there has to be an outer float, and it still threatens to break out of its container...
Putting It Together

First, this code gets added to the CSS stylesheet:

<style type="text/css">

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

</style><!-- main stylesheet ends, CC with new stylesheet below... -->

<!--[if IE]>
<style type="text/css">
.clearfix {
zoom: 1; /* triggers hasLayout */
} /* Only IE can see inside the conditional comment
and read this CSS rule. Don't ever use a normal HTML
comment inside the CC or it will close prematurely. */
</style>
<![endif]-->

For the HTML, just add a class of .clearfix to any element containing a float needing to be cleared, plus any Guillotine-Bug-fixing block elements within the container. That's it! It's not perfect, but it's a whole lot better than adding an entire extra 'dummy' element. Check out this live demo of the fix in action:

IE/Mac Strikes Back

All this is wonderful, but unfortunately IE for the Mac does not "auto-clear" floats, and also does not support :after, and so is left out of the clearing party. What's to be done?

You might callously abandon IE/Mac, but consider that many people who use older Macs can't run Safari, or several other modern browsers. Thankfully this browser has been dropped by Microsoft, and at some future time the numbers of such IE/Mac users will become miniscule. Remember that even if a float appears to stick out of a container, no content will actually be obscured. It just won't look as pretty for those few viewers, that's all. Each author will have to decide on this issue according to their specific needs.

This page once described a Javascript method to force compliance in IE/Mac, but now thanks to Mark Hadley and Matt Keogh it's now possible to dispense with that ugly Javascript and go with a straight CSS fix. Woohoo!
Taming the IE/Mac Float Problem

Basically the fix is just a matter of applying a display: inline-block; to the .clearfix class, and hiding that property from all other browsers. That's it! We can easily do this with our existing code, slightly modified.

<style type="text/css">

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

.clearfix {display: inline-block;} /* for IE/Mac */

</style><!-- main stylesheet ends, CC with new stylesheet below... -->

<!--[if IE]>
<style type="text/css">
.clearfix {
zoom: 1; /* triggers hasLayout */
display: block; /* resets display for IE/Win */
} /* Only IE can see inside the conditional comment
and read this CSS rule. Don't ever use a normal HTML
comment inside the CC or it will close prematurely. */
</style>
<![endif]-->

The .clearfix {display: inline-block;} is seen by all browsers, and fixes IE/Mac. Then, inside the rule set that is hidden from IE/Mac, the display is reset to block. That's all she wrote! Simply stick the above code into your CSS, and use .clearfix on any box that has to contain a sizable float. Ain't that cool? Just watch out for previous external floats triggering the IE Float Model, as mentioned earlier.

Kudos to Alex Robinson for finding that inline-block is superior to the older inline-table fix for IE/Mac.
A Word Of Warning (this is important!)

The W3C float specification requires that a cleared element shall stay below all previous floats. There are no exceptions to this requirement! "Previous" in this case means any float that comes earlier in the source document.

Up until November of 2004, Firefox was still incorrectly clearing only the floats that were vertically above the clearing element, rather than all previous floats. This meant that in those earlier Gecko browsers you could place a floated column down one side of the screen, and inside another column (possibly another floated column) you could clear a smaller interior float, without that cleared element dropping below the previous floated column. Since only Gecko had this problem, it was obvious that something was wrong every time this happened to a page. Normally Gecko is the good browser, but in this one case it was the culprit. See, IE is not always the bad guy!

However, this easy clearing method has muddled the issue quite a bit, since now Explorer is not actually being cleared at all, while Gecko browsers have finally been corrected so they do clear all previous floats.

...Oh no! Do you see what will now happen in our hypothetical float page? IE, seeing no real clearing elements, will look great. Meanwhile, in newer Gecko browsers and Opera 7, the CSS generated clearing element in the first easycleared box will drag the height of that box waaaay down the page, until that invisible clearer is vertically below the bottom of the previous float column (assuming there is a bottom!). This can "generate" a huge empty space inside that once-small easycleared box, depending on the actual height of the neighboring float column.

Of course Opera 7 has always correctly implimented the clearing specs just like IE does (aside from bugs), and the Mac browsers are not involved either. If you are wondering how this issue can be fixed, well, it can't. Gecko and Opera are now both following the float clearing specs correctly, and IE only fails because of the faked "clearing" we are forcing upon it.
Preventing External Clearing

If you have the above described problem, one way to prevent the clearer from clearing the adjacent float column is to make the container a float itself. Of course once you float the container you no longer need easyclearing, sigh...

Note that when all the main elements in a column setup are floats, the worst IE float bugs simply do not happen. Thus using an all-float approach to column design can actually be easier to accomplish, at least within a rigid-width layout.

Source : http://www.positioniseverything.net/easyclearing.html