How to Center a Website with CSSThe question about centering your website in the visitor’s screen always comes up. Fortunately, the solution is really very simple.

Essentially, you can have two different types of website layouts -  fixed and liquid widths. Fixed widths stay, well…fixed. Liquid layouts stretch to suit the size of your visitor’s screen.

How to Center Liquid Layouts

Liquid layouts are very simple to center. Assuming you have a main container div in place, simply set the left and right margins the same, like the following, for example:

div#container {
  margin-left: 20%;
  margin-right: 20%;
}

How to Center Fixed-width Layouts

Fixed-width layouts work a bit different from liquid layouts. According to the W3C, “If both ‘margin-left’ and ‘margin-right’ are ‘auto’, their used values are equal. This horizontally centers the element with respect to the edges of the containing block.”

div#container {
  margin-left: auto;
  margin-right: auto;
  width: 900px;
}

In other words, setting the margin-left and margin-right properties to auto should center your webpage. However, because older versions of IE are so nice to web developers, they ignore auto margins completely. To fix this, centering the body content does the trick nicely.

body {
  text-align: center;
}

The problem with this is that now all your page’s content is centered. To fix this, just reset the alignment of the container div.

div#container {
  margin-left: auto;
  margin-right: auto;
  width: 900px;
  text-align: left;
}

What about “div#container”?

Now all you have to do is wrap a “container” div around your entire page’s content, like so.

<body>
  <div id="container">
    <!-- your content goes here -->
  </div>
</body>