To horizontally center a block element (like <div>), use margin: auto;
Setting the width of the element will prevent it from stretching out to the edges of its container.
The element will then take up the specified width, and the remaining space will be split equally between the two margins:
See this example:
Note: Center aligning has no effect if the width property is not set (or set to 100%).
To just center the text inside an element, use text-align: center;
See this example:
One method for aligning elements is to use position: absolute;:
See this example:
Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
Tip: When aligning elements with position, always define margin and padding for the <body> element. This is to avoid visual differences in different browsers.
There is also a problem with IE8 and earlier, when using position. If a container element (in our case <div class="container">) has a specified width, and the !DOCTYPE declaration is missing, IE8 and earlier versions will add a 17px margin on the right side. This seems to be space reserved for a scrollbar. So, always set the !DOCTYPE declaration when using position:
See this example:
Another method for aligning elements is to use the float property:
See this example: