By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

How to Center a Website or Element

How to center individual elements and entire layouts, using nothing but clean CSS.

Edited: 2014-10-30 18:37

This article is about centering of elements, and also explains how to Center a website using CSS.

Centering individual elements can be done by applying a margin, and setting it to auto, this will however not work in older versions of IE.

Older versions of Internet Explore, mainly prior to IE7, dose not support centering with margin. But at the same time, they have a bug where text-align also works on block elements.

Centering using margin

All modern browsers support centering using margin. This is done by setting the margin property of elements to auto, along with a width.

The below CSS will center a div element with an id of "Basement", which is used as the container of the page. But you can also use the same CSS on other elements then the main container.

#Basement {
  width: 800px;
  margin: auto;
}

A fully working example is shown below.

<!DOCTYPE html>
<html lang="en-US">

  <head>
    <title>How to Center a Website</title>
    <style type="text/css">
     #Basement {
      width: 800px;
      margin: auto;
     }
    </style>
  </head>

  <body>
   <div id="Basement">
    <article>
      <h1>How to Center a Website</h1>
      <p>My first Website.</p>
    </article>
   </div>
  </body>

</html>

Brugbart Vision!

Older versions of Internet Explore

Note. Brugbart strongly recommends that you advice your users to upgrade their browser, rather then apply this fix.

This is a centering fix for Internet Explore, which uses text-align to center a child element.

The below CSS would center elements in versions of Internet Explore prior to IE7. This is done by applying text-align: center; to the parant element of the element you want centered. This would however also center the text of the child, which is why you also need to reset the text-alignment on the child element.

Note. that IE7 doesn't have this problem if you remembered to include a doctype.

body {
  text-align: center;
}
#Basement {
  width: 800px;
  text-align: left;
  margin: auto;
}

Note that i left the margin in place, this is because text-align won't center elements in modern browsers, including current versions of IE.

The final example not recommended:

<!DOCTYPE html>
<html lang="en-US">

  <head>
    <title>How to Center a Website</title>
    <style type="text/css">
     body {
      text-align: center;
     }
     #Basement {
      width: 800px;
      text-align: left;
      margin: auto;
     }
    </style>
  </head>

  <body>
   <div id="Basement">
    <article>
      <h1>How to Center a Website</h1>
      <p>My first Website.</p>
    </article>
   </div>
  </body>

</html>

Brugbart Vision!