CSS Align
Aligning Block Elements
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:
- <h1>
- <p>
- <div>
In this chapter we will show you how to horizontally align block elements for layout purposes.
Center Aligning Using the margin Property
Block elements can be aligned by setting the left and right margins to "auto".
Note: Using margin:auto will not work in Internet Explorer. See the next step in this tutorial for a crossbrowser fix.
Setting the left and right margins to auto specifies that they should split the available margin equally. The result is a centered element:
Example
|
Tip: Aligning has no effect if the width is 100%.
Crossbrowser Compatibility Issues
There is a bug in Internet Explorer's handling of margins for block elements.
In IE, block elements are sometimes treated as inline content. This is particularly problematic when it comes to centering.For centering to work in IE, use the text-align property.
To avoid this affecting the text in the original <div>, add a new <div> as a container with text-align:center, and reset the text-align in the original <div>:
Example
|
Now the code for centering a block element works in all browsers!
Left and Right Aligning Using the position Property
One method of aligning elements is to use absolute positioning:
Example
|
Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
Crossbrowser Compatibility Issues
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 also another problem with IE 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, IE 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:
Example
|
Left and Right Aligning Using the float Property
One method of aligning elements is to use the float property:
Example
|
Crossbrowser Compatibility Issues
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 also another problem with IE when using the float property. If the !DOCTYPE declaration is missing, IE 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: