Centering a Page with CSS

August 14th, 2006 by Trevor

There's a very simple way to center a web-page horizontally, using only a smidgen of CSS:

body {
margin: 0px auto;
width: 760px;
}

Comments

Posting code? Please use Pastie.

Have a question? Please visit the Forum.

4 Comments

  1. Well,

    i think that
    body {
    margin: 0px auto;
    width: 760px;
    }

    it’s not good. Try thees solutions:

    layout with “pixel”


    body{
    margin:0;
    padding:0;
    text-align:center; /* IE5.x/Win fix */
    }
    auxiliary{
    width: 760px; /* summary of all width, padding border, margin of what is in itself */
    margin-left:auto;
    margin-right:auto;
    text-align:left ; /* IE5.x/Win fix: it restores the corrected alignment */
    }

    layout with “fluid”


    body{
    margin:0;
    padding:0 10%;
    }

    Well, i thin that, the second Css is easer than first.

    Bye.

    P.S.I’m sorry for my english :-P


  2. The two CSS solutions can be used for different situations. You may not want to set your body width narrower than the full width of the browser depending on your layout, in which case you would want a container element centered within the body. The “text-align: center;” IE Win fix in the body tag is also a wise move. Both solutions will work, depending on your needs, but the second, in my experience, is more flexible and cross-browser.


  3. as new to web design I can’t understand how to implement the codes.

    Comment by ollyss on September 4, 2006

  4. ollyss, try this page out: http://www.w3schools.com/css/default.asp

    Comment by Trevor on September 4, 2006