Friday, August 31, 2012

CSS Two Column Layout (via Bootstrap)

The other week I was worrying about the best way to setup two vertical columns using CSS. Most of the resources online are outdated and refer to IE5.5 on Mac and other such antiquities. I turned to twitter, and Chad Kittel suggested just do what Bootstrap does. What Would Bootstrap Do is the most recent WWxD addition to my vocabulary.

So I went digging and here is the results.
Float both columns and use :before and :after to contain things.

The default two columns layout in Bootstrap floats both columns to the left. There is no reason you couldn't change it, but it makes the most sense to keep your code readable and flexible. Adding more columns is simple and it flows the way you'd read.

The largest challenge in the two column layout is keeping things on top and on bottom where they belong. The old stand by is display:none to contain columns but you can hide things that you'd actually want to see. It isn't something I've run into very often, but on occasion I have. My biggest problem with display:none is that is has always felt like a hack and the problem with simple hacks is designers tend to abuse them (they end up everywhere).

All the common browsers support the :before and :after pseudo classes but unfortunately IE7, which enough of our customers still use, doesn't. Fortunately, that is easy to work around without a technical hack.

Here is my class formatted for LESS.

.contain {
    &:before, &:after {
        content: "";
        display: table;
        line-height: 0;
    }
    &:after {
        clear: both;
    }
    *zoom: 1;
}
The work was already done in Bootstrap, but I found a better explanation of the basic ideas from this clearfix page. Basically, if you wanted bare-bones support the single line of :after is all you need. The :before and :after table stuff helps to properly use margin and padding. The zoom puts the block into a special mode on IE7 to contain your floats.

No comments:

Post a Comment