Monday, 29 November 2010

Simple method of horizontally centering a DIV of unknown width

Centering in CSS is always a pain. If you are just centering text, or you are using (god forbid) IE6 then you can simply use the text-align property. If you are centering something of a known width, it's easy too, just set margin-left and margin-right to 'auto' and all is good. However, if you don't know how wide the element is going to be, for example, you have an element that expands to fit some text pulled from a database, it's a bit tricker.

There are loads of hacks around of varying reliability and complexity, but the simplest method I have found yet is the following.

  • The outer div is set to text-align: center

  • The inner div is set to display: inline-block



That's it. The fact that the inner div is set to inline-block means it picks up its parent's setting of text-align to center itself. Is kinda wierd, but works on all the browsers I've so far tested.

1 comment: