How to Center Align Div Tag Element Using CSS?

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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Tips4weblife.blogspot.com</title> <style type="text/css"> <

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

<body>

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

2 comments:

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

Nat Pavasant said...

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

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

body { text-align: center; }