CSS-Plus
CSS-Plus
Play with web technologies

How to horizontally center elements of a dynamic width

May 21, 2012
Attention: This article is old and the content is outdated. I've left the article here for historical purposes.

A couple of months ago I wrote an article titled "How to horizontally center anything with CSS". The featured method of the article was to center an element with a dynamic width using display: table. This works wonderfully in IE8+ and modern browsers. I would usually ignore IE7's inability to render this property, however, every now and then it would have to work in IE7. This is an example of the display: table method:

New Method

Ever since I came across the IE7 inline-block hack, I've been using it whenever I can. It works in IE7, why wouldn't I use it everywhere?

Inline-blocks can be centered with the use of text-align: center. Therefore, a list of inline-blocks can be centered extremely easily. This works absolutely wonderfully for horizontally centered navigations, or anything that doesn't have block level elements within it. This is an example of a navigation dynamically centered with the use of inline-block elements and the text-align: center property:

You may have noticed that the HTML doesn't have spaces between the elements for readability like the previous example does. This is because the elements are treating the spaces/enters/tabs between them as an actual space since they are behaving like inline elements. IE7 doesn't support inline-block, however an inline element which receives hasLayout behaves as if it were an inline-block. zoom: 1 is one of the properties which forces hasLayout on an element in IE.

Conclusion

This is an extremely simple way of solving a dynamically centered navigation problem with brilliant browser support. It may not be the solution for every display: table that is/was used, but it can definitely help in a bunch of different scenarios.