How do I center a block on the page  PDF Print E-mail
Tag it:
Delicious
Furl it!
Digg
NewsVine
Reddit
YahooMyWeb
Technorati
Articles Reviews CSS
Written by Rachel Andrew   
Saturday, 17 November 2007

A common page layout has a fixed-width  centered box that contains the page content, how can we center this box on the page using CSS?

You can use CSS to center a fixed-width box by setting its left and right margins to auto.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Centered Box</title>
<meta http-equiv="content-type"
    content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="center.css" />
</head>
<body>
<div id="content">
    <p>This is an example text for How do I center a block on the page article </p>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing …</p>
</div>
</body>
</html> 

body {
    background-color: #CCD3D9;
    color: #000000;
    text-align: center;
}
#content {
    width: 630px;
    margin-left: auto;
    margin-right: auto;
    border: 2px solid #A6B2BC;
    background-color: #FFFFFF;
    color: #000000;
    padding: 0 20px 0 20px;
    text-align: left;
}

This technique allows you to center a box easily, and is ideal if you need to center a content block on a page.

When we set both the left and right margins to auto, we are asking the browser to calculate the margins necessary to make them equal, thereby centering the box. In “How do I create a fixed-width, centered, two-column layout?”, we’ll see how to create a layout inside a container that has been centered in this way.

The example code provided here contains additional CSS that works around a bug in IE 5.x that prevents the margins from centering content. By setting textalign: center on the body, then setting it back again (text-align: left) on the content <div>, we are able to work around the problem, allowing the layout to center in these browsers as well.


User reviews

Average user rating from: 1 user(s)

Overall rating
5.0
 

Add new review



0 of 0 people found the following review helpful

Thanks!, Wednesday, 02 April 2008

Written by Dave

Overall rating
5.0
Centering content on a page has been bothering me for some time yesterday. My dev PC is not connected to the internet, so I was roughing it out trying to 'hack' my way into centering the page content. Of course I failed and wasted plenty of time.

This article helped me immediately and has added a tool to my currently mini css mental toolbox. Not sure how much more time I would have wasted without it.

Thanks!
Was this review helpful to you? yes     no


Powered by jReviews

Last Updated ( Saturday, 20 September 2008 )
 
< Prev   Next >