How I Learned to Stop Floating and Love the inline-block

Angelo Simeoni

Floating columns is a typical approach to defining page layout. The obvious issue with floating columns is clearing said floats. When you start dealing with the details of auto-clearing elements and browser inconsistencies, you might start to desire an alternate approach.

Clearing issues & browser inconsistencies aside, floating is not the natural way to define layout. Floating is intended to be used to allow inline elements to wrap around floated elements.

Float Example

When floats are used for layout, things can break if the contents of one column is greater than that of another.

Floated Layout Example

Inline-block to the rescue. Inline-block is another display type that offers several advantages to floating layouts.

  • simple, maintainable grid-based system of layout
  • vertical-align columns (top, bottom & middle)
  • no clearing floats

However, inline-block has its own set of quirks.

  • markup is whitespace sensitive
  • display of child elements in firefox 2 can be tricky

''

That being said, here’s how to define inline-block for understanding browsers.

.inline-block {
  display: inline-block;
}

As with most things, it isn’t that easy. First obstacles: IE6 & IE7.

<!--[if IE]>
  .inline-block {
    zoom: 1;
    display: inline;
  }
<![endif]-->

The zoom: 1; causes a state proprietary to IE called hasLayout to have a value of true. hasLayout is a shallow, fickle beast, but suffice to say that the preceding two rules will cause the affected boxes to behave as inline blocks in IE6 & IE7. Why? It kind of just does. There are reasons why, but it’s much easier just to accept this one.

Caveat: Inline elements are white-space sensitive. To avoid this issue in IE, make this:

<div class="inline-block">

some text
</div>
<div class="inline-block">

some text
</div>

into this:

<div class="inline-block">

some text
</div><div class="inline-block">

some text
</div>

Firefox 3 and Safari 3 have implemented inline-block according to the CSS 2.1 spec. Firefox 2: not so much. For reasons we won’t get into here, Firefox 2 removed support for inline-block. There are, however, a slew of proprietary mozilla extensions for display. Most are meant for use with XUL, part of the actual Firefox application, but two of these allow us to create blocks that behave like inline-blocks.

.inline-block {
  display: -moz-inline-box;
  -moz-box-orient: vertical;
}

(-moz-box-orient determines the orientation of children elements.)

Final CSS:

.inline-block {
  display: inline-block;
  display: -moz-inline-box;
  -moz-box-orient: vertical;
  vertical-align: top;
}
<!--[if IE]>
  .inline-block {
    zoom: 1;
    display: inline;
  }
<![endif]-->

vertical-align defines how the boxes line up - either at the top, middle, or bottom of the tallest inline-block box. Inline-block example.

This technique works in IE6, IE7, Firefox 2, Firefox 3, and Safari 3.