How can I center a div within another div? [duplic

2020-01-27 10:27发布

I've got an problem. I have the html code like this:

<div id="main_content" >
    <div id="container">
    </div>
</div>

The css like this:

#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;
}

I suppose that the #container will be centered within #main_content. However, it is not. I just want to find out the reason and how to make it centered.

标签: html css
27条回答
甜甜的少女心
2楼-- · 2020-01-27 11:26

I would try defining a more specific width, for starters. It's hard to center something that already spans the entire width:

#container {
  width: 400px;
}
查看更多
Juvenile、少年°
3楼-- · 2020-01-27 11:26

This will work fine i think though you might need to reset "top:200px;" according to your need--

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

#container {
width: 100px;
height: 20px;;
margin: 0 auto;
padding-top: 10px;
position: relative;
top:200px;
border:2px solid #cccccc;
}
查看更多
Emotional °昔
4楼-- · 2020-01-27 11:27

Without setting the Width it will get the maximum width it can get. So you cannot see that Div has centered.

#container 
{
  width: 50%;
  height: auto;
  margin: auto;
  padding: 10px;
  position: relative;
  background-color:black;  /* Just to see the different*/
}
查看更多
登录 后发表回答