How to Center a DIV Using CSS
This technique works whether the DIV contains, images, text, or combination of both, by using Cascading Style Sheets (CSS).
Steps to Centering a DIV Block
Start by coding the DIV you wish to center.
<div id="box"> This is a DIV that we plan to center using CSS. </div>
Now to make the DIV Block center, you must do the following:
- Set a width for the DIV Block
- Add a margin to force centering
Both steps are required, because without setting a width to the DIV the margins alone will not force the DIV to center.
#box { width: 500px; margin: 0 auto; }
For the example I used pixel as the width, but you may also use percentage or em. Results will be the same.
Result: Centered DIV Block
By using the code, we were able to center a DIV Block.
This is a DIV that we centered without the text doing the same.
Browser Support
This method has been tested in Firefox, IE 6, 7,Safari and Opera.
