CSS way to focus my div

I have a div that sits at the top of the webpage, but the div should be centered horizontally.

But for some reason, the div is always sitting on the left?

Do you know how I can make a div sit in the center horizontally?

If I add "align =" center "" to the div, it will be centered, but I'm looking for a clean CSS way to make it centered:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml"> <head> <title> </title> <style type="text/css"> <!-- body { text-align: center; margin: 0 auto; background-color: RGB(197, 155, 109); background-image: url("../images/bodyBk2Lite.png"); background-repeat: repeat; font-family: "Arial", "Tahoma", Serif; font-size: 17px; } p { text-align: left; } #heading { width: 100%; height: 110px; background-image: url("../images/headingBk2Lite.png"); background-repeat: repeat-y; background-color: RGB(0, 0, 0); } #headingContainer { width: 980px; height: 110px; text-align: right; background-color: red; } #headingSpacer { height: 15px; } --> </style> </head> <body> <div id="heading"> <div id="headingContainer"> <a href="index.html"><img src="images/headingImg.png" height="105px" alt="Select Recipes"/></a> </div> </div> </body> </html> 
+4
source share
4 answers

You can use automatic stock since the element has a width of:

  #headingContainer { margin: 0 auto; width: 980px; height: 110px; text-align: right; background-color: red; } 

http://jsfiddle.net/Xee6s/

+5
source

Yes, margin: 0 auto; this is good, but you should leave text-align: center in your body for an older browser like IE

+1
source

You can align divs in the center by setting margins on the left and right on the car. this forces the browser to share the space equally

 #heading { width:200px; margin:0 auto 0 auto; } 

In jsfiddle: http://jsfiddle.net/DfXBp/1/

+1
source

Assuming you're trying to center the div #heading or #headingContainer in the center, just add their styles:

 margin: 0 auto; 
+1
source

All Articles