Centering Your Design Using CSS

by | Feb 15, 2009 | CSS

Having learned the hard way, IE doesn’t like the easy way of doing things. Therefore, here’s a quick fix when you want to create a centered design where it will work in both IE and FF as well as other browsers.

First, some basic HTML for how your page would be laid out:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
  “https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <meta http-equiv="content-type" content="text/html;
  charset=utf-8" />
  <title>Centering a website using CSS</title>
  <style type="text/css">
    #CSS goes here#
  </style>
</head>
<body>
Your content would go here
</body>
</html>

In a next step we create the element we want to center in the browser window. In this case I’ve chosen a generic div which migth serve as a container for your website’s content in a later step.

<div id="maincontent">DIV to be centered</div>

After creating all necessary structural markup we can now focus on the CSS part of this tutorial. First of all we will define some basic properties of the body as well as of our container element.


body {

  background: #fff;

  color: #000;

  font: 0.7em/160% “Lucida Grande”, Verdana, sans-serif;

  margin: 0;

  padding: 0;

}

#maincontent {

  background: #dded86;

  width: 400px;

}

The div should now be displayed as a 400px wide box with a light green background. In a next step we set the horizontal margin of the respective element to “auto”, which causes the browser to display it in the center of the browser window — well, at least in most of the browsers.


#maincontent {

  background: #dded86;

  width: 400px;

  margin: 0 auto;

}

In order to make IE also center the box, we have to append the property text-align: center to the body rule. Make sure that you also append text-align: left to the maincontent rule in order to prevent the browser from also centering the content of the div. That’s it.


body {

  background: #fff;

  color: #000;

  font: 0.7em/160% “Lucida Grande”, Verdana, sans-serif;

  margin: 0;

  padding: 0;

  text-align: center;

}

#maincontent {

  background: #dded86;

  width: 400px;

  margin: 0 auto;

  text-align: left;

}

0 Comments

Pin It on Pinterest

Share This