How to Center a Layout in CSS

on Thu Dec 04 23:15:49 GMT 2008 in XHTML and CSS and viewed 18339 times

A very basic tutorial on how to center layouts in CSS. A very useful technique for many layouts.


Many people don’t know how to center their layouts when using CSS and DIVs. I myself had a lot of problems. But this is the way to do it:

First you need this code in your BODY tag, so in your stylesheet you’ll need to put this inside the body:

text-align:center;

So it’d look like

BODY { text-align:center; }

Then you need one big DIV to encompass the whole layout. So put this in your stylesheet:

#layout { margin-left:auto; margin-right:auto; }

Now when you want to do anything, just do this:


  <div id="layout">
  <!--Your layout here-->
  </div>

What this will do is create a unique element called layout to be used, and says that there’s a margin to the left which will be automatically defined, and the right will be automatically defined as well. Now this will also center all the text in each element. So to counter this, just put text-align:left; or whatever it is you want in each element that will have text.

So the whole code will end up being:


  <style type="text/css">
  BODY { text-align:center; }
  #layout { margin-left:auto; margin-right:auto; }
  #element { text-align:left; background-color:#000; color:#FFF; width:770px; height:50px; }
  </style>

  <div id="layout">
  <div id="element">
  This is text.
  </div><!--end element-->
  </div><!--end layout-->

I added some stuff, like a little box to show that text will show up aligned to the left like it usually is. So now you can experiment around with this stuff. Have fun!