Center Div or Other Objects with CSS

/* Posted June 20th, 2008 at 3:01pm */
/* Filed under CSS */

/* */

blurry zoom css effect

CSS is a powerful method to describe the look and layout of a webpage but as versatile as it is, being able to center an object isn’t immediately obvious. Unlike HTML, which has an explicit centering tag, namely

<div align="center"></div>

no such mechanism exists in CSS. After a bit of research, I found out how to do it. Simply use the margin-left and margin-right properties. If you set them to the same value, that “centers” your object, be it a div or anything else.

div
{
margin-left: 50px;
margin-right:50px;
}

But what if you have a fixed width div object and you want it to vary the left and right margin based on the browser screen size? The answer is simple:

div
{
margin-left: auto;
margin-right:auto;
}

will do the trick. With auto, the values are always set to something equal and will automatically be determined based indirectly through the other layout properties you provide.

  • Twitter
  • Digg
  • del.icio.us
  • Propeller
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • Mixx
  • Yahoo! Buzz
  • NewsVine
  • Facebook
  • Google Bookmarks

Related Posts


Related Videos

Basic HTML and CSS… Faster HTML and CSS:… Build Native iPhone Apps… HTML/CSS/JavaScript is…

Related Stories

Related Tweets

One Response to “Center Div or Other Objects with CSS”

  • Comment from Messoriti

    ?????? ??????? ? ? ????? ( ?????????? ????????? ???? ????? ????) ???? ????????? ??? ??????? ? ????? ???? ??????????????, ???? ????? ??????? ???? ???? ? ???????????? ????, ??? ??? ????? ????? ?? ????? ???????? ?? ??????. ????? ?????, ?? ??????


Leave a Reply

or Login (not required)





HTML tags allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>