How can I center a div within another div?
css, html
Solution
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:
- auto - CSS reference | MDN
- margin - CSS reference | MDN
- What is the meaning of `auto` value in a CSS property - Stack Overflow
In action at jsFiddle.
Problem
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> ```