How to center a containing block on a page using CSS

csstutorial

If you want to know how to center a containing block on a page using CSS, here is the solution!!

There are two main methods and the choice is yours.

Centering liquid layouts

Liquid layouts are easy to center using margins on each side of the containing box. The margins can be set with em, pixel or percentage units.

div#container
{
        margin-left: 10%;
        margin-right: 10%;
}

Centering fixed-width layouts

Theoretically, you should be able to apply auto margins to the left and right of the containing block and it should center on the page.

Accordning to W3C Visual formatting model “If both ‘margin-left’ and ‘margin-right’ are ‘auto’, their used values are equal. This horizontally centers the element with respect to the edges of the containing block.”

A containing block should be able to be centered using the following rules:

div#container
{
        margin-left: auto;
        margin-right: auto;
        width: 50em;
}

By adding two simple rules, this problem can be overcome in all of the browsers mentioned above, excluding NN4.

1. Center the body

While these browsers ignore auto margins, they will follow “text-align: center”. If this is applied to the body, the containing block will center correctly. So, a new rule is added:

body
{
        text-align: center;
}
 
div#container
{
        margin-left: auto;
        margin-right: auto;
        width: 50em;
}

2. Resetting text-align

The only problem with this new rule is that all content on the page is now center-aligned. To overcome the center alignment pills without prescription problem, a new declaration is added within the containing block rule set – “text-align: left”. The final CSS code is:

body
{
        text-align: center;
}
 
div#container
{
        margin-left: auto;
        margin-right: auto;
        width: 50em;
        text-align: left;
}

About the author

p has written 30 articles for popkha.com

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>