CSS Align Using Margin

You will often want to center align a block element (such as a div). Personally I find the best way to do this is to use CSS Align Using Margin.

Setting a margin to auto will try and force the element to the opposite side. So, if you set both left and right margins to auto, the browser will put the browser in center.

Let’s take a look at the follow example CSS code, to be applied to a block element like a div:

.centerme{
  width:100px;
  margin-left:auto;
  margin-right:auto;
}

It is very important you set a width on the element. You cannot center align something that takes up the full width of it’s container. Imagine a room full of water, you cannot make the water go into the center of the room without forcing its sides in. Bit of an odd analogy, but you get the meaning.

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • FriendFeed
  • LinkedIn
  • Live
  • MSN Reporter
  • MySpace
  • PDF
  • Ping.fm
  • Posterous
  • Reddit
  • RSS
  • Slashdot
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Technorati
  • Tumblr
  • Twitter
  • Yahoo! Bookmarks
  • Yahoo! Buzz
This entry was posted on Friday, January 29th, 2010 at 12:14 am and is filed under CSS Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Post a Comment