Centre a DIV Block using CSS Styling

Print Friendly


Working on some templates these days, one of the most painful thing i found was styling the div containers. While styling the DIV containers, one of the roadblock was to centre align a DIV. At first i thought its as simple as adding text-align styling to center for that div as below:

#divToBeAligned {
    text-align: center ; 

However, the rule centres the text inside the box, instead of the block itself. This was causing the block to stay at the same position but internal contents to be aligned center, which is not as I desired i.e. centre the entire block but leave the internal contents formatted as it was before.

To center the block in CSS i had to do the following:

1. Specify a width for the DIV block.
2. Set both its left and right margins to auto.

When both margins are set to auto, web browsers are required by the CSS standard to give them equal width.

For example, if you want your div block to have a width of 526px pixels, the following code will centre the block.

#divToBeAligned {
  width: 526px ;
  margin-left: auto ;
  margin-right: auto ;

This will get the block in the shape you want. Happy Styling 🙂

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)