A block element is an element that takes up the full width available, and has a line break before and after it.
Examples of block elements:
For aligning text, see the CSS Text chapter.
In this chapter we will show you how to horizontally align block elements for layout purposes.
Block elements can be center-aligned by setting the left and right margins to "auto".
Note: Using margin:auto; will not work in IE8 and earlier unless a !DOCTYPE is declared. |
Setting the left and right margins to auto specifies that they should split the available margin equally. The result is a centered element:
Tip: Center-aligning has no effect if the width is 100%.
One method of aligning elements is to use absolute positioning:
Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
When aligning elements like this, it is always a good idea to predefine margin and padding for the <body> element. This is to avoid visual differences in different browsers.
There is a problem with IE8 and earlier, when using the position property. 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. Always set the !DOCTYPE declaration when using the position property:
One method of aligning elements is to use the float property:
When aligning elements like this, it is always a good idea to predefine margin and padding for the <body> element. This is to avoid visual differences in different browsers.
There is a problem with IE8 and earlier when using the float property. If 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. Always set the !DOCTYPE declaration when using the float property: