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.
<h1 style="text-align: center;">
My Heading
</h1>
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,
<p style="text-align: center">
<img src="carrotman.gif" />
</p>
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).
<h1 style="margin-left: auto; margin-right: auto;">
My Heading
</h1>
<h1 style="margin-left: auto; margin-right: auto; width: 50%;">
My Heading
</h1>
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.
<h1 style="text-align: center">
X
</h1>
<h1 style="margin-left: auto; margin-right: auto;">
Z
</h1>
<h1 style="margin-left: auto; margin-right: auto; text-align: center;">
Y
</h1>
Summary
margin-left: auto; margin-right: auto;
centers a block level element.text-align: center;
centers the inline content of a block level element.- MSIE has bugs that result in it treating block level content as inline content (for centring) under some circumstances.
Updated: 3-24-09