Learn CSS3 to style your web pages

Know what is CSS, its uses and how to add? CSS Style for Text, Paragraphs, Tables, Links and Forms. Background image with CSS, Borders styles in CSS, Set margin and positions in CSS, etc.

CSS Align Elements


Center Align Elements

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:

.center {
    margin: auto;
    width: 50%;
    border: 3px solid green;
    padding: 10px;
}

Note: Center aligning has no effect if the width property is not set (or set to 100%).


Center Align Text

To just center the text inside an element, use text-align: center;

See this example:

.center {
    text-align: center;
    border: 3px solid green;
}

Left and Right Align - Using position

One method for aligning elements is to use position: absolute;:

See this example:

.right {
    position: absolute;
    right: 0px;
    width: 300px;
    border: 3px solid #73AD21;
    padding: 10px;
}

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:

body {
    margin: 0;
    padding: 0;
}

.container {
    position: relative;
    width: 100%;
}

.right {
    position: absolute;
    right: 0px;
    width: 300px;
    background-color: #b0e0e6;
}

Left and Right Align - Using float

Another method for aligning elements is to use the float property:

See this example:

.right {
    float: right;
    width: 300px;
    border: 3px solid #73AD21;
    padding: 10px;
}