Centering Elements via CSS

Sep 7

Centering Elements via CSS


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.


Comments

by Joe,   September 8, 2004 8:49 AM  

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.


by Joe,   September 8, 2004 8:49 AM  

Also, I take it you have bunnies at your place again?


by Deane,   September 8, 2004 9:33 AM  

"Also, I take it you have bunnies at your place again?"

Nah. I just like bunnies. They're furry.


by zoogies,   August 10, 2005 10:48 PM  

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

Thanks to all who participated.

Want to advertise on this site? Contact FM.