How can I center a div within another div?

user2142709 picture user2142709 · Mar 13, 2013 · Viewed 353k times · Source

I suppose that the #container will be centered within #main_content. However, it is not. Why isn't this working, and how can I fix it?

#main_content {
  top: 160px;
  left: 160px;
  width: 800px;
  min-height: 500px;
  height: auto;
  background-color: #2185C5;
  position: relative;
}

#container {
  width: auto;
  height: auto;
  margin: 0 auto;
  padding: 10px;
  position: relative;
}
<div id="main_content">
  <div id="container">
  </div>
</div>

Answer

ShuklaSannidhya picture ShuklaSannidhya · Mar 13, 2013

You need to set the width of the container (auto won't work):

#container {
    width: 640px; /* Can be in percentage also. */
    height: auto;
    margin: 0 auto;
    padding: 10px;
    position: relative;
}

The CSS reference by MDN explains it all.

Check out these links:

In action at jsFiddle.