Centering items via CSS
Centering items is a frequent task when designing websites. But for people that are new to CSS it’s mostly kind of enigma how to center for example a whole website in browsers other than IE. For this reason I’ve created a short tutorial on how to achieve this task using pure CSS.
Basic HTML
In a first step we create the basic HTML including a valid doctype. For this tutorial I’ve chosen XHTML 1.0 Strict. Make sure that nothing precedes the doctype in order to prevent IE from switching back to quirksmode. If you are not familiar with using doctypes check out this excellent article on A List Apart.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns="http://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>
</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>
CSS
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;
}
