且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将div定位在另一个div中?

更新时间:2022-10-21 09:53:21

您需要设置容器的宽度。 ( auto 将无法使用)

  #container {
width:640px; / *也可以是百分比。* /
height:auto;
margin:0 auto;
padding:10px;
position:relative;
}



查看这些链接




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.

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

Update - In action @ jsFiddle