How to center your page with CSS - horizontally

October 9th, 2008

Centering a page horizontally is pretty easy with CSS. Vertically is a little more difficult, actually it can be a lot more difficult. I like to build websites with fixed widths, I don’t know why, but to me they just look better. I like the frame a background around the content adds to the site. Whitespace should be your friend. So, unless you want all of your webpages to sit on the absolute left edge of the browser, you’re going to want to center your page’s content horizontally.

For your HTML, you’re going to set up your page like any other, and you’re going to wrap all of your page content in a wrapper div, or a container.

HTML <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" “http://www.w3.org/TR/html4/strict.dtd”> <html> <head> <title>Your Page Title</title> <link rel=”stylesheet” href=”styles/default.css” type=”text/css” media=”screen” charset=”utf-8″> </head> <body> <div id=”wrapper”> your page content </div><!–end wrapper–> </body> </html>

CSS body {padding: 0; margin: 0; text-align: center; background: #369;} div#wrapper {width: 850px; margin: 0 auto; background: #fff; text-align: left;}

That’s it, all you need to center your content on the page, but keep your text aligned to the left. For most modern browsers, the margin of auto for the left and right sides would be enough to center your content on the page, but for browsers like ie6, you have to use the text-align: center on the body tag. It doesn’t recognize the auto, but it does apply text-alignment to block elements like divs.

Tags: ,

2 Responses to “How to center your page with CSS - horizontally”

  1. CSS, Dreamweaver & background - Webmaster Forums - Webmaster forum for HTML, PHP, ASP, CSS and more Says:

    October 10th, 2008 at 11:17 pm

    [...] Centering a site horizontally is pretty easy, I actually wrote a post yesterday on how to do this. Center your page content. As for making columns, the trick is to float them all to the left or right, left is more natural, [...]

  2. lollielala Says:

    October 14th, 2008 at 8:58 pm

    Sweet thanks - Absolute frustration
    when ya don’t know this.(like I didn’t)

Leave a Reply

Name:

Email (will not be published):

Website:

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