CSS Introduction | CSS Position Properties | Align
Align
You can use the following methods to align block-type elements.
- Center alignment using the
marginproperty - Left and right alignment using the
positionproperty - Left and right alignment using the
floatproperty
Center Alignment Using the margin Property
When the margin property value is set to auto, the element is horizontally centered based on the container element that wraps it.
At this time, the element must have a specific width, and the remaining space except for the width is divided evenly to the left and right as margins.
Therefore, to use this method, you must first set the width property value of the element.
<style>
div { width: 300px; margin: auto; }
</style>
In Internet Explorer 8 and earlier, the <!DOCTYPE html> tag must be inserted in the HTML document for the margin property to be displayed correctly.
Left and Right Alignment Using the position Property
An element positioned with absolute positioning leaves the normal layout and can overlap other elements. Using this characteristic, you can align HTML elements horizontally to the left or right.
When aligning with the position property, it is recommended to set margin and padding values on the <body> element.
This helps prevent the layout from appearing differently in each web browser.
<style>
div { width: 300px; padding: 10px; margin: 0; position: absolute; right: 0; }
</style>
In Internet Explorer 8 and earlier, the <!DOCTYPE html> tag must be inserted in the HTML document for the position property to be displayed correctly.
Left and Right Alignment Using the float Property
With the float property, you can align elements horizontally to the left or right.
When aligning with the float property, it is recommended to set margin and padding values on the <body> element.
This helps prevent the layout from appearing differently in each web browser.
<style>
div { width: 350px; padding: 10px; margin: 0; }
div.left { float: left }
div.right { float: right }
</style>
In Internet Explorer 8 and earlier, the <!DOCTYPE html> tag must be inserted in the HTML document for the float property to be displayed correctly.