Farewell Floats: The Future of CSS Layout

by on 29th June 2011 with 51 Comments

Floats are one of the most basic tools for structuring a web page using CSS. They’re both one of the very first things that we learn about and one of the last things that we truly master.

Today’s article looks at some of the reasons that floats are pretty lame and takes a look at a number of alternative layout systems, some of which are still under development but may one day represent the standard for CSS-based layout.

A Tale of Tables

Once upon a time, web designers used HTML tables to accomplish complex page layouts. Though it was a messy, non-semantic process, it attempted to make the best of the available technology to create better designs.

For newbies, when I say “non-semantic,” I mean that table-based layout is a bastardization of the table element. It’s meant to hold actual tables of information within a page, not to serve as the structure for the page itself.

Floats: The New Tables?

Today, we scoff at this practice. What a silly way to lay out a website! CSS has come to our rescue and provided us with several tools for creating much more semantic layouts that can easily achieve anything that was created with a table.

Today one of the primary ways that we have replaced our table-dependent ways is the use of floats for layout. By default, sequential HTML elements will appear vertically stacked. Floats serve as a way for us to line elements up horizontally. Float a list of li elements to the left and you’ve got yourself a nice little horizontal navigation menu.

Though many of us have simply grown accustomed to using them, floats are far from ideal. They’re awkward, buggy and difficult to learn. If you think back to when you first began CSS-based layout, the thing that had you scratching your head and troubleshooting for hours was probably a float gone wrong.

The Clearfix Band-Aid

The bane of float-based layouts (aside from IE6 margin nightmares) is of course the fact that they simply don’t play well with their container elements. In order to get the parent element to appear as if it contains floated elements, we typically insert a cleared element last in the container using “clear:both”.

Is creating an empty container to hack a broken layout a good practice? Probably not. Does it work? You bet.

A Better Clearfix

Forward thinkers have decided that this business of adding additional HTML markup is no good. The current favorite way to clear a float is to instead insert the new element using the CSS “:after” pseudo class.

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

Once again, this is acceptable because of how accustomed we are to messing with floats to bend them to our will. However, try taking a step back and really looking at what’s going on here. This is a mess! We’re using CSS to insert an invisible element into the HTML so that our layout problems magically disappear as we shiver at the thought of using table-based layouts because they aren’t semantic.

I’m not defending table-based layout, it’s dead and needs to stay that way, but I can’t help but wonder if future web designers will laugh at our use of floats the way that we now laugh at the thought of a web page built on a table.

The Future

You have to admit, if you really think about it, floats are a pretty screwed up and complicated way to handle page layout. I don’t see floats going completely away any time soon, they’ll likely still be useful even if we all do accept a new layout process.

However, there are several interesting layout tools on the horizon that could very well replace floats as a primary way that to structure web pages. Let’s take a look at some of these ideas and constructs and see if we can get a glimpse into what the future of CSS layout will be like.

Inline-Block

Before we dive into futuristic experimental layout techniques, it’s worthwhile to discuss inline-block as an interesting alternative to float-based layouts. Consider the snippet below:

ul li {
    display: inline-block;
    width: 100px;
    min-height: 100px; 
    vertical-align: top; /*helps with variable length content*/
} 

This will actually cause our list items to appear inline while retaining their block attributes, which is completely amazing really! We get the best of both worlds.

Downfalls of Inline-Block

Andrew Tetlaw from Sitepoint recently published a fantastic article that highly praises using inline-block over floats. He correctly points out that this method works effectively on all modern browsers, including IE8 and above, which is about the same as you can expect from the pseudo-class-driven clearfix from above.

Unfortunately, as Robert Nyman points out in a similar article, this method isn’t without its problems.

In addition to the IE troubles (he has a clever hack to get support in IE7), Nyman shows using inline-block causes your layout to be somewhat whitespace dependent when it comes to your HTML. The example he uses is the following unordered list:

  • Item one
  • Item two
  • Item three

Believe it or not, the line returns automatically cause a slight margin to be added to the list items! The only way to fix it is to place them on the same line:

  • Item one
  • Item two
  • Item three

Admittedly, it’s a fairly easy fix, but if you’re a fan of neatly organized code, this may make you cringe. On the whole, when compared to the trouble that we face using floats, Tetlaw has a point that this may be a better solution that you can actually use now with an acceptable amount of browser support.

Flexbox

One of the new ways that CSS3 is changing layout practices is through the Flexible Box Module, or Flexbox for short. Here’s a quote from the Flexbox w3 abstract.

[Flexbox] provides an additional layout system alongside the ones already in CSS. [CSS21] In this new box model, the children of a box are laid out either horizontally or vertically, and unused space can be assigned to a particular child or distributed among the children by assignment of “flex” to the children that should expand. Nesting of these boxes (horizontal inside vertical, or vertical inside horizontal) can be used to build layouts in two dimensions.

Flexbox represents a completely new way to layout websites. You may have heard about this recently but the syntax is changing a bit so make sure you keep an eye on the working spec to stay up to date (I believe “box” will change to “flex” or “flexbox” in most cases). The current working CSS syntax for applying flexbox is as follows:

display: box;
display: -webkit-box;
display: -moz-box;

To see how it works, let’s jump right into an example. Basically, once you apply display: box to the parent element, the children can be automatically redistributed based on simple relative sizing.

Imagine we have three paragraph tags (these will serve as columns) inside a parent container with display: box applied and we want the middle column to be twice the width of the other two. Here’s what we do:

#box2 {
    -webkit-box-flex: 1;
    -moz-box-flex: 1;
    box-flex: 1;
}

With that little bit of code (plus some superfluous visual styling), we can achieve the following result.

screenshot

Note that the default value is “0” for box-flex. Changing the second box to “2” triggered the command to fill the width while making the second box wider than the other two. Let’s consider a few more examples so you can really get a feel for how it works.

screenshot
screenshot
screenshot

As you can see, Flexbox has dramatic implications to the way we structure websites with CSS. Not only does this have the potential to solve the problems associated with floats, it makes multi-column grid-based layouts infinitely easier!

Dig Deeper

This article is merely meant as an introduction to new layout methods and is not in any way exhaustive. I’ve barely scratched the surface of what what Flexbox can do. For instance, you can accomplish the same thing we did above with vertically stacked elements and completely rearrange the boxes using only CSS.

For more on what can be done with Flexbox, I highly recommend that you play with Flexie, The Flexbox Playground. This will give you hands-on experience with the new layout system and allow you to try each setting to get a feel for the result.

The Template Layout Module

Another proposed idea for CSS layout is the Template Layout Module. Here’s a quote from the official spec.

“The properties in this specification work by associating a layout policy with an element. Rather than letting an element lay out its descendants in their normal order as inline text or as blocks of text (the policies available in CSS level 1), the policy defined in this module, called template-based positioning, gives an element an invisible grid for aligning descendant elements.”

The Template Layout Module uses a quirky but straightforward syntax that makes layout a breeze. The first thing you need to do is create a container with some child elements. For each child element, you assign an arbitrary letter (it doesn’t matter which letter, just make sure they’re unique).

#div1 {
    position: a;
}

#div1 {
    position: b;
}

#div1 {
    position: c;
}

Next, you apply a display value to the parent element using these letters to define your proportions. For example, to create three equal columns, simply type them all in a row:

#container {
    display: "abc";
}

This will give you the following result:

screenshot

If you want to rearrange the boxes, simply rearrange the letters in your CSS. Instead of typing “abc”, try typing “bca”.

screenshot

To create a new row, create a new set of quotes. You can repeat letters to set a sense of proportion. For instance, here we set the first row to “ab” and the second to “cc”, meaning “c” will be twice the width of “a” or “b”.

screenshot

Each section (a,b,c) is referred to as a “slot”. To create an empty slot, simply use a period: “a.b.c” will create two empty slots in our row. To target a slot for additional styling, you use the slot pseudo element:

#container::slot(c) {background: gray;}

Dig Deeper

As with the previous example, there’s a lot more that can be done here such as setting heights and widths using precise dimensions or percentages. None of it is ready to use in any browser at the moment but you can install a jQuery plugin to test it out! Check out the plugin’s demo pages for some awesome coded examples of how to create any layout you want using the Template Layout Module.

Back to Tables?

The Andrew Tetlaw Sitepoint article that I mentioned before presents one more interesting option for layout.

.nav > ul {
  display: table;
  border-spacing: 0.25em;
}

Interestingly enough, setting the “display” property to “table” allows us to structure our layout as if they were tables. Right away I know this is going to freak a lot of people out. Reverting back to table-based layout!? Are you nuts? The crazy part is though that this is in fact a completely different practice than literally using a table element. Here you’re simply telling the CSS to position elements similarly to how table cells and rows are positioned.

Personally, I still like the new fancy CSS3 methods that we just covered a lot better and really have a hard time imagining this gaining widespread acceptance, but it’s worth checking out and discussing nonetheless. If you’re interested, be sure to check out Tetlaw’s explanation.

Conclusion

The point of this article was to get you thinking about how floats may not necessarily be the best way to structure websites. Though they’re one of the best solutions that we can currently use in live client projects, they represent a fairly sloppy and broken system that is far from ideal.

There are a number of ways that you can address the downfalls of floats. For now, you could check out “display: inline-block” as one option or even look into “display: table” if you’re particularly brave.

The wizards that make all this technology work recognize that the system is broken and are hard at work solving the problems with layout modules that may prove extremely useful in the future. Expect to hear a lot more on the Flexbox and Template Layout modules in the future. Who knows, one or both of these could be the standard way that future developers create web layouts!

Leave a comment and let us know your thoughts on all this. Do you think floats represent a flawed layout system? Do any of the proposed layout modules seem like a solid fix for these issues?

Comments & Discussion

51 Comments

  • http://devblog.terracycle.net/author/rcannon/ Robin Cannon

    A really nice piece there, and great to see such a comprehensive overview of float alternatives. Certainly as CSS develops we’re becoming more and more capable of getting away from the often awkward float property.

    I also think that for column based sites (particularly those when you know one column will be longer than, say, the sidebar) there remains a place for position:absolute. It provides a lot of potential flexibility of layout.

  • Bryan

    Love the knowledge I attained from this

  • http://www.getcreativewebdesign.com/blog/ Elise

    What a great, informative article…thank you! I look forward to using these new methods in the future.
    I certainly don’t want to get caught using the modern equivalent of tables if there is a better solution!

  • http://michael.mior.ca Michael Mior

    My current favourite method of clearing floats is overflow:auto on the parent. Doesn’t always work, but more often than you’d think!

  • http://erichessdesign.com Eric Hess Design

    I literally had no idea about these new methods! Definitely will have to start experimenting with these… Very cool! Earned a Retweet!

  • http://www.inspirawebdesign.com Mike

    Dunno, although not the easiest part of CSS to learn, I like to think I have the gist of floats by now and I don’t find them all that terrible to use.

  • http://www.justforthealofit.com/ TheAL

    I read about and dabbled with replacing the clear:both fix with :after back in 2008. I assumed it was getting a bit old. I’ve noticed a lot of people using PNG tricks and things like overflow:hidden on the parent. All sorts of messy weirdness.

    I am really looking forward to solid solutions and things like Flex Box. Things that just freaking work the way we want. Want three boxes in a parent that fill parent with equal widths and heights regardless of amount of content, and grow with parent? Why should that be so hard to do without tricks and gimmicks?

  • egiova

    Very informative post. We will probably ended with pre-established classes for margins and paddings (kind of grid thing), and flexbox. I made some experimentations too, but it always brokes after 4 or 5 columns, with or without paddings or margins indeed. I didn´t figure out yet how to make the “display:table” works. But “inline-block” is yet well known. Thanks for the overview, well done.

  • http://www.cranialstudios.com Benjamin Ulrich

    Flexbox seems useful, especially considering current design trends of Golden ratios, etc. :)

  • http://www.ehometips.com rajeev verma

    Thanks for this tutorial on floats.I struggle a lot with IE.Personally i think world will be a happier place with only Firefox in it.

  • http://tesmond.blogspot.com/ Andrew

    Actually I quite like the -ms-grid layout http://blogs.msdn.com/b/ie/archive/2011/04/14/ie10-platform-preview-and-css-features-for-adaptive-layouts.aspx

    The flexbox is also fun.

    There are only two problems with table layouts

    1. the lack of display flexibility for multiple devices

    2. The “semantic” problem as aluded to above, but this does “only” affect screen readers rather than your general audience. Only web designers or screen readers who come to your site will be upset with a table layout everyone else is fine.

    The table layout is used so often because it is much simpler and cross browser capable (and by cross browser I really mean IE6 :)) than floats, and for most sites the target audience does not care how it is displayed, just that it is displayed!

    I think the ms-grid property is actually the best method to replace table layouts. They are just as easy to understand and just as capable as tables without the above problems…if only large institutions such as the NHS were not still using IE6 we could all move to a brighter semantically correct future.

  • Gaël

    The display:table property is very well documented on ie7nomore.com, and display:table-cell // display:table-row too.
    This model is very useful, and it’s ready to use in all browsers since IE8, so I often use it and I recommend its usage !

  • http://jetsuseink.com Justin

    I’m a fan of using overflow:hidden on the container around the floated elements. The only issue is when you want each column to be the same height which takes some crazy usage of html styling and min-height.

    The Flex Box and Template Layout methods look like a breath of fresh air. I’m looking forward to those catching on.

  • Alex

    Nice article!

    but overall i think its just another way of trying to get the same results.

    I love floats and i can do anything with floats. Can’t think of a reason to try different since there isn’t a layout out there i can’t code

  • Matt

    Oh dear, oh dear. What an awful way to begin an otherwise interesting article. Can I suggest you go read up on what “semantic” means (in the context of web design), then come back and apologise to “newbies” for making such a newbie mistake. “symantec layout” indeed.

  • http://escope.eu escope

    This post is actually very lame. Sorry that i must start this way, but i cant understand what is so difficult about floats … In ie6 dor example you can fix the double margin problem on floated elements using display:inline (it will still be floated,but this display property fix this bug). About the parent element… You dont have to use :after … Come on its not even supported by all browsers. Instead add overflow:hidden to the parent and he will strech on height according his floated children (when using this dont add height to the parent). This is it, its simple enought :)

  • http://twitter.com/mike_ebert Mike Ebert

    I think that Flexbox is decent and that the Template Layout Module is crappy alphabet soup. display:table isn’t the best either, as it forces a particular source order on your content.

    My favorite option, unfortunately, has a ways to go until we see it in browsers. Have you seen this editor’s draft of a W3C spec? http://www.interoperabilitybridges.com/css3-grid-align/ Grid Alignment seems to be the best solution I’ve seen so far.

  • http://cronco.me Mihai

    Another thing you can try with display:inline-block; to avoid whitespace dependency is to set font-size:0 on the container. (if it is purely a container that doesn’t hold any text on it’s own). Works like a charm.

  • Tonttu

    @Mike Ebert: I understand the Microsoft grid proposals are getting fused and this will replace the Template Layout Module and the alphabet soup will still be an option. Correct me if I’m wrong. I like the alphabet soup thing as I did ascii and ansi art as a kid :D

  • http://www.4muladesign.com/ Jamie Brightmore

    I’ve played around with Flexbox and really like it. The Template Layout Module is a new one on me, looks very interesting.

    Great post, thank you.

  • http://www.boogdesign.com/b2evo/ Rob Crowther

    Note that box-flex:2 doesn’t automatically make an element twice as wide as one that is box-flex:1, it only looks like that because all the elements you’re demonstrating with have a small intrinsic width. Flexbox distributes the leftover space between the elements, it doesn’t distribute the total width.

  • Tim Avery

    All of these are achieving the same thing just in a different manner. At the time that tables were the way of the world, EVERYONE used tables and that was just that. Then floating divs became the way of the world and currently that is the easiest, most concise, and reliable way to code a website. I disagree with the comment:

    “They’re awkward, buggy and difficult to learn”

    In fact I would say the opposite, in that they are simple, fairly stable, and quite easy to learn. I’ve never heard a web designer or developer, say, “dang these floats are killing me, I just can’t figure it out.” The “hacks” used to work around small issues are jsut part of the game. In 5 years when the next new way to lay things out is popular people will be saying the same things, “oh there has to be something better”.

    The truth is the vast majority of web developers and designers just make due and don’t give a second thought to it. I for one could care less what I am using to layout the code for a site–as long as it looks good and functions how I envision it, then the way I got there doesn’t matter all that much to me. If the code is an atrocious mess that would be a different story, but as is you can do a really nice job with what is available–and with the popular float method.

    I am not saying that floats are the “ideal” way to do things; but in reality for what we have and what is available, they really are the easiest thing to use.

  • terry

    I am really pleased to see this development as the current CSS box model is an over complicated mess for layout. I’ve been struggling to get my head around CSS for days since I’m a CSS novice but I’m quite familiar with server-side programming. The CSS styling is pretty straight forward and works but the layout is a complete nightmare.
    The thought that kept coming up in my head:”There has GOT to be a better way. Why is it so hard to accomplish something so simple?” This definitely gives me hope for the future.

  • Aankhen

    Andrew: “The “semantic” problem as aluded to above, but this does “only” affect screen readers rather than your general audience. Only web designers or screen readers who come to your site will be upset with a table layout everyone else is fine.”

    Laying something out like a table using CSS does not affect the semantics of the page. Web designers who are upset about it fail to understand this very basic distinction. Not sure what screen readers have to be upset about either.

  • Mark

    The root of the silliness of this article: “Though many of us have simply grown accustomed to using them, floats are far from ideal. They’re awkward, buggy and difficult to learn.”

    If you really think so, then maybe you’re only doing it wrong.

  • http://www.jja-holzwerkstatt.de/ Landhausdielen

    I can´t wait to implement such things. Really easy. I don´t have the time to follow the CSS3 train, but I see what it will mean to us. Can you put a browser compatiblity table please?

  • http://marktyrrell.com Mark Tyrrell

    Surely the ‘clearfix’ problem is a rendering fault of the web browser?

    I’ve always felt overflow:hidden/auto was a solution that made sense, anyone able to explain why it’s considered messy?

  • http://heptagrama.com Tedel

    Sounds interesting, as interesting as a blogger who once pointed out a full CSS layout with list items only. We would have to wait to see it browser-compatible and implement-able; and I’d like to see how would this mix with HTML5 too.

  • http://www.datosperu.org Peru

    I fully agree: floats are gone. The “now” is css and html5 like the one here: http://www.datosperu.org
    Its light, homogeneous and can do almost everything you need.

  • Matt Ritter

    Mark Tyrrell:

    I agree with you. I haven’t used a clearfix in over a year. the overflow:auto property almost always solves any wrapper issues I have with floats.

  • http://www.alexgalinier.com Alex Galinier

    Good article.

    I don’t like float, really not ! I use often the “display:table” method but i love the future that Flexbox represent.

  • http://webdesignbusinessbuilder.com/ Heath Howard

    Great stuff, thanks for the info. The inline block is too much of a hack, where you are using something in a way it wasn’t meant to be used.

    I will have to check out the Flexbox and display methods though.

  • Jake_canton

    We can fix the “downfalls of Inline-Block” by css. Unfortunately I found that there’s 1px problem in Opera (IE6 and IE7 is OK).

  • http://uykusuzadam.wordpress.com Abdurrahman

    Good future of CSS :) from new css student, thx

  • http://www.anstudio.ca Andre Beriault

    Love all your articles, they are very informative, although sometimes scary, as we see things moving too fast for our regurlar business. Personnaly I love floats for my “fluid” designs; I believe that was their reason in the first place. See my photos collection using left aligned floats: http://www.aberiault.com/html-fr/collection-ART.html
    Keep up your very inspiring work
    Cheers
    Andre

  • Brian

    This clearfix code is standard in many base Drupal themes, and works in every browser we’ve tried… it’s a combination of the :after and inline-block techniques

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

    .clearfix { display: inline-block; }

    /* Hides from IE-mac \*/
    * html .clearfix { height: 1%; }
    .clearfix { display: block; }
    /* End hide from IE-mac */

    (Normally I avoid “hacks” like the IE-Mac bit above like the plague, but make an exception for this one case. You could remove it if you don’t care about IE-Mac)

  • JonO

    “Here you’re simply telling the CSS to position elements similarly to how table cells and rows are positioned.”

    And then there was the professor who devoted his life to proving that Shakespeare’s plays weren’t written by William Shakespeare, but by another playwright of the same name.

  • Danno

    Table layout is definitely not dead.

  • http://jaysonlorenzen.wordpress.com Jayson Lorenzen

    Thanks for taking time to do this comparison. Template Layout Module, looks good to me, will follow that more for sure.

  • ObjectiveCat

    For those interested in seeing CSS table implemented in a major website,
    apple.com is using display:table and table-cell for their main navigation bar and the links contained within.

  • http://chrisburnell.com Chris Burnell

    Highly informative article; I look forward to the future of CSS!

  • Colin

    A point to consider for all web designers. Try reading your web pages with a screen-reader. This will really make you think about the way you lay out a web page.

  • Paul

    We don’t use tables even though they’ve been ’round for so long and very stable, because all the cool kids are using [insert new cool tech here].

    Like the Emporer’s New Clothes, nobody wants to admit that *tables* are still cool for fearing that they won’t appear cool. Sooner or later some kid’s gonna yell, “the Emporer’s not wearing any clothes!”.

    You almost yelled it out in this blog, a little muffled, and behind your hand, and not quite loud enough for the Emporer to hear!

  • Bill

    Interesting stuff… The Flexi box was easy to sort out but I couldn’t get the Template Layout Module to work. A little HTML along with the CSS would be a great help.

    Thanks for the article,

    Bill

  • Tope

    you can use
    overflow: auto;

    instead of adding invisible elements..

  • http://www.ericmwelch.com Eric W.

    great article, I learned a lot. Floats have been a source of frustration more than once for me. I’m pretty excited about these new options for layout.

    Bookmarked, thanks

  • http://www.finelysliced.com.au Ray

    If you apply a width and overflow:hidden to the parent, the floats are cleared. No extra markup. Job done.

  • T

    I like the template layout but the jquery plug-in doesn’t seem to work for any jquery version after 1.4. :(

  • http://viajeenbus.com/ viaje en bus

    travel to peru by bus.

  • http://www.321auto.ro/ 321auto

    Thank you for this tuto. Realy useful!

  • http://johanvancura2206.soup.io/post/454388123/Basic-Points-to-Undertake-when-Booking-a website

    After checking out a handful of the blog posts on your
    blog, I truly like your way of writing a blog. I bookmarked it to
    my bookmark webpage list and will be checking back in the near future.
    Take a look at my web site too and let me know what you think.

Subscribe
Membership
About the Author