How do I center a div in CSS in a stylesheet while following standards?

3 answers

danwellman 5600
5
points
This was chosen as the best answer

As long as it has a specified width you can use margin:auto to center it in whatever container it is in -

.center {
  width:600px; /* an arbitrary width, it can be any width */
  margin:auto; /* center it! */
}
Answered about 7 years ago by danwellman
  • Don't forget that if you support IE6 and you are centering something horizontally you will need to set the parent elements text-align:center and float:none; on the child element you want centered. margin:auto is not supported in IE6 Mark Malek about 7 years ago
  • @Mark Malek - That's only true if you're authoring your page in quirks mode, which - in 2009 - you'd be crazy to do. Here's a little more info http://www.quirksmode.org/css/quirksmode.html Andy Ford about 7 years ago
Jojo 15
3
points

Another method, if you know the width/height of the element you're trying to center:

#myCenteredDiv {
    position: absolute;
    width: 100px;
    height: 100px;
    left: 50%;
    top: 50%;
    margin-top: -50px; /* Should be half the height of the element */
    margin-left: -50px; /* Should be half the width of the element */
}
Answered about 7 years ago by Jojo
  • This method is great if you need to support IE6. Mark Malek about 7 years ago
0
points

I'm not sure if you want to center it within the whole page or within another div, but there is the method for the entire page, which, if modified slightly will also center within a div:

body {
    margin: 0; /* it's good practice to zero the margin and padding of the body element to account for differing browser defaults */
    padding: 0;
    text-align: center; /* this centers the container in IE 5* browsers. The text is then set to the left aligned default in the #container selector */
}
#container { /* this is the centered div */
    width: 780px;  /* using 20px less than a full 800px width allows for browser chrome and avoids a horizontal scroll bar */
    margin: 0 auto; /* the auto margins (in conjunction with a width) center the page */
    border: 1px solid #000000;
    text-align: left; /* this overrides the text-align: center on the body element. */
}
#mainContent { /* this is the div where you'd put content so it isn't right against the borders of the container div, although this isn't needed */
    padding: 0 20px;
}

<body class="oneColFixCtr">
    <div id="container">
      <div id="mainContent"></div>
    </div>
</body>
Answered about 7 years ago by Darryl Hein