Home
Home | Blog

iHwy Development Blog

The iHwy team shares their musings about their development experiences.

Centering a div using CSS

Posted on May 14, 2008 15:54 by Jack

Centering a block of content is a common requirement when laying out a web page, but it's often not completely obvious how to do it. Here's a common way we do it, which has worked nicely for us:

For the HTML:

The "wrapper" is the container that the div you want to center will be inside of. The "block" is the div that contains your content.

<div id="wrapper">
<div id="block">
This div is centered inside it's parent div.<br/>
This div is centered inside it's parent div.<br/>
This div is centered inside it's parent div.<br/>
This div is centered inside it's parent div.<br/>
This div is centered inside it's parent div.<br/>
This div is centered inside it's parent div.<br/>
</div>
</div>

For the CSS:

Here's the styling for the wrapper and the block. Comments are included to help you understand how it works.

* { margin:0; padding: 0 } /* shortcut browser reset: optional */
#wrapper { 
text-align:center;        /* centers the #block */
padding:10px 0;           /* to separate the blocks a bit for this example*/
border:1px solid green;   /* to help you see the border */
}
#block { 
text-align:left;          /* removes the centering from #wrapper
width:250px;              /* width of your block
margin:0 auto;            /* 'auto' equalizes the left and right margins
border:1px solid red;     /* to help you see the border */
}

Here a screenshot of the results:

centeredDiv