Centering Elements via CSS

By Deane Barker on September 7, 2004


Here’s a CSS technique that I didn’t know about, and perhaps you didn’t either. To center an element on the page — like the image above — just set the margins to “auto.” This only works on block elements, so you’ll need to modify the “display” value for images.


img.center
{
  display: block;
  margin: auto;
}

If you want a fixed width site running down the center of the page:


div.container
{
  width: 760px;
  margin: auto;
}

Handy. Again, this may be obvious to a lot of people, but I apparently managed to avoid learning about it for the last six years. It was difficult to remain that oblivious, but I’m tenacious that way.

Gadgetopia

Comments

  1. There are often IE quirks that keep this from working. To get around it, you place text-align: center on an outer element, and text-align:left on the element itself (so the contents flow normally within your centered element). IE will flow the block element like text, but other browsers will use the margin:auto method.

  2. shakes head

    After all this time, all I needed to do was add display:block…thanks to you and google, my life is now that much easier =)

Comments are closed. If you have something you really want to say, email editors@gadgetopia.com and we‘ll get it added for you.