[ # ] Center Div or Other Objects with CSS
/* Posted June 20th, 2008 at 3:01pm *//* Filed under CSS */

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.













Leave a Reply
(* required)