Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS way to centre my div

I have a div that sits at the top of a webpage, but the div is meant to b centred horizontally.

But for some reason the div always sits to the left?

Do you know how I can get the div to sit centred horizontally?

If I add "align="center"" to the div then its sits centred but I am looking for a pure CSS way to make it centred:

<!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>
like image 915
sazr Avatar asked Feb 22 '23 14:02

sazr


2 Answers

You can use an automatic margin as the element has a width:

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

http://jsfiddle.net/Xee6s/

like image 134
Clive Avatar answered Mar 02 '23 19:03

Clive


Yeah the margin: 0 auto; is good but you have to leave the text-align:center in your body for older browser like IE

like image 33
GregM Avatar answered Mar 02 '23 19:03

GregM