In CSS, several properties can be used to align elements horizontally.
Center Align - Using margin
Setting the width of a block-level element will prevent it from stretching
out to the edges of its container. Use margin: auto;
, to
horizontally center an element within its container.
The element will then take up the specified width, and the remaining space will be split equally between the two margins:
Example
.center
{
margin: auto;
width: 60%;
border: 3px solid #73AD21;
padding: 10px;
}
Try it Yourself »
Tip: Center aligning has no effect if the width
property is not set
(or set to 100%).
Tip: For aligning text, see the CSS Text chapter.
Left and Right Align - Using position
One method for aligning elements is to use position: absolute;
:
Example
.right
{
position: absolute;
right: 0px;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
Try it Yourself »
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
:
Example
body
{
margin: 0;
padding: 0;
}
.container
{
position: relative;
width: 100%;
}
.right
{
position: absolute;
right: 0px;
width: 300px;
background-color: #b0e0e6;
}
Try it Yourself »
Left and Right Align - Using float
Another method for aligning elements is to use the float
property:
Example
.right
{
float: right;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
Try it Yourself »
Tip: When aligning elements with float
, 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 float
. 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. So, always set the !DOCTYPE
declaration when using float
:
Example
body
{
margin: 0;
padding: 0;
}
.right
{
float: right;
width: 300px;
background-color: #b0e0e6;
}
Try it Yourself »