English-only | Jenom česky | Bilingual/Dvojjazyčně

CSS Hack: Inline Blocks

There is an important difference between inline elements (em, strong, a, span; anything with display:inline) and block elements (hX, p, li, div; anything with display:block) in their padding and border formatting. While block's position includes its border and padding, the position of an inline element includes only horizontal paddings and borders. The vertical ones are drawn around the content after the element has been placed on the proper position on the line.

Block / Blok:

Lorem ipsum dolor sit amet.

Inline:

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet.


Unfortunatelly, MSIE/Win uses this correct formatting since the version 6. The older versions (5.5, 5, and previous) don't display padding and borders around inline elements at all. Let's compare the example above in MSIE5 and in MSIE6:

Comparing inline formatting in MSIE

Fig. 1: Inline formatting of previous example in MSIE 5 (left) and MSIE 6 (right)

However, there is a workaround for MSIE. If we set the width property (which should be ignored in inline elements), IE internally changes the element's type to display:inline-block (which is fully supported practically in MSIE only). From the point of view of the element itself it's a block — but from the point of view of the element's neighbourhood it's still an inline element.

.bordered {
   width: 1em;
   background: yellow;
   padding: 1em;
   border: 1px solid black;
   }
...
<p>
   Lorem ipsum dolor sit amet.<br />
   Lorem ipsum <span class="bordered">dolor</span> sit amet.<br />
   Lorem ipsum dolor sit amet.
</p>

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet.


In fact, the width acts as minimal width (min-width) here. All browsers (but IE5) will ignore it, and IE5 will stretch the width if the content is wider (until there is breakable whitespace in the content, otherwise the text is broken into new line).

Inline block in MSIE 5

Fig. 2: Inline block in MSIE 5, with vertical-align:middle added (top right); text containing a breakable whitespace (bottom left) and without it (using the &nbsp;) (bottom right).

We can reach the same effect by setting the display:inline-block but other browsers than just IE5 could use it then (IE6 supports inline-block and more browsers may support it in the future). We can also use the underscore hack to set additional properties for IE only.

In real, we use just tiny vertical padding in inline elements (usually several px only). The smaller the vertical paddings and borders are, the more the inline blocks in IE5 are similar to inline elements in other browsers. You can an example of using this "hack" in the "Inline buttons" article.