Important Docs

Centering using CSS

Methods for centring block and inline elements using Cascading Style Sheets

Introduction

Back in the days of HTML 3.x and the transitional variants of HTML 4.x and XHTML 1.0 a number of elements supported the align attribute. How it acted depended on what element it was applied to and there is no direct translation for CSS. How you center elements depends on the type of element.

Please note that for conciseness the examples in this document make use of inline style. In practice inline style is not encouraged and you should use external style sheets.

Inline Content

Inline content includes such things as text, images, and <span>. To center inline content use the CSS text-align property applied to a block level container with the content to be aligned inside. Yes, it is badly named. "inline-align" would probably have been a better choice. Point of clarification: While the text-align property is applied to the <h1>, the content it positions is what's inside the element, not the element itself. So, for example, centers the image, not the paragraph.

Block Level Content

Block level content includes such elements as <h1>, <h2>, <p>, <table>, and <div>. To center block level elements set their left and right margins to auto (but see IE Bugs). However, the default width for most block level elements is auto, which fills the available area on screen. Just being centerd places it in the same position as left alignment. If you wish it to be visually centerd you should set a width (or a max-width although Internet Explorer 6 and earlier do not support this, and IE 7 only supports it in standards mode).

Inline Content and the Block Holding It

A common mistake people make after reading this article is to think "I want to center the text inside my <h1>, it is a block, therefore I must alter the margins.". For clarification then, I will repeat: text is inline content.

In the above image there are three block level elements. To make it clear what is happening their width is constrained (remember: this is not the default except for tables) and a border is added.

The top element (X) has its inline content centerd. By default most block level elements, <table> being the obvious exception, are as wide as the space available to hold them, so this would usually center the content on screen. The bottom element (Z) is centerd itself using the block technique. Note that the text inside is still left aligned. If the width was not constrained, this centring would have no visible effect on the element. The middle element (Y) has both its inline content centerd and is centerd itself with the block technique.

Summary

Updated: 3-24-09