You Are Here: Home »Tutorials»General »   Css Centering

CSS Centering

Fixed Width Divs

This is one of the easiest ways I know of to center a fixed-width div that works in IE, Mozilla and Opera (and probably most other major browsers) and it's a pretty simple concept.

First of all just a regular fixed-width centered div, something that might be a stand-alone box rather than a container for other content.

<!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" lang="en" xml:lang="en">
<head>
<title>CSS Centering - Example 1</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
body {
     margin:0;
     padding:0;
     background:#000 }

#center {
     top:50%; /*top offset*/
     left:50%; /*left offset*/
     width:600px;
     height:400px;
     background:#fff;
     position: absolute;
   
     /* this needs to be 50% of your total width, in this case 600px */
     margin-left: -300px;
   
     /* and the same for the height */
     margin-top: -200px }
</style>
</head>
<body>
  <div id="center"></div>
</body>
</html>

Which would turn out like this

Secondly a 100% high example, expanding on the same method. This would be ideal as a container for all other content as the height of other elements can then be set within it, just using height:100% in a content div can cause overflow problems if you have columns of different lengths:

<!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" lang="en" xml:lang="en">
<head>
<title>CSS Centering - Example 2</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
body {
     margin:0;
     padding:0;

     /* this sets a guide for all elements used within the container */
     height:100%;
     background:#000 }
     
html>body #outer{ height:auto } /*needed for mozilla*/

#outer {
     left:50%; /*left offset*/
     width:760px;
     height:100%;

     /* stops overflow when one column is longer 
	    than the other for elements inside this */
     min-height:100%;

     background:#fff;
     position: absolute;
   
     /* again 50% of your total width, in this case 760px */
     margin-left: -380px }
</style>
</head>
<body>
  <div id="outer"></div>
</body>
</html>

Which would turn out like this

And we're done.