How to Center Align Div Tag Element Using CSS?


If you're creating your design using css instead tables you could probably run into problem how to center div element in your page. There is no such css rule float:middle which probably could help to center this div.

The solution is very simple in fact. All you have to do is to define margin: 0 auto; property in your css code. For example you have some div like

<div id="container"> Content </div>
and want to center it in the page. In your CSS zone type:

.container{ width: 860px; margin:0 auto}
The result would be as shown in the picture bellow

css centering div block

You can test it out by copying the code below to your text editor (i.e. Notepad) and save it with .html extension.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> <

#container { width: 860px; margin: 0 auto; background:#999999; } </style> </head>


<div id="container"> <p>Content</p> </div> </body> </html>


Anonymous said...

Great, this one works well for IE7, Firefox, Opera (the 3 browsers I tested so far).
Hopefully it is OK with IE6. If somebody can check... Thanks

nat3738 said...

No, it won't work in IE6.
But the following code work.

(Only the CSS)
{ width: 860px; margin: 0 auto; background:#999999; text-align: left; }

body { text-align: center; }