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条回答
Anthone
2楼-- · 2020-01-27 11:21
.parent {
width:500px;
height:200px;
border: 2px solid #000;
display: table-cell;
vertical-align: middle;
}
#kid {
width:70%; /* 70% of the parent*/
margin:auto;
border:2px solid #f00;
height: 70%;
}

This does solve the problem very well (tested in all new browsers), where the parent div has class="parent" and the child div has id="kid"

That style centers both horizontally and vertically. Vertical center can only be done using complicated tricks--or by making the parent div function as a table-cell, which is one of the only elements in HTML that properly supports vertical alignment. Simply set the height of the kid, margin auto, and middle vertical alignment, and it will work. It's the easiest solution that I know.

查看更多
forever°为你锁心
3楼-- · 2020-01-27 11:22

You can center float div with this little code:

#div {
width: 200px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;

margin-top: -100px;
margin-left: -100px;
}
查看更多
\"骚年 ilove
4楼-- · 2020-01-27 11:22

everyone said it but i guess it won't hurt saying again. you need to set the width to some value. here is something simpler to understand.

http://jsfiddle.net/XUxEC/

查看更多
走好不送
5楼-- · 2020-01-27 11:23

It is because your width is set to auto. You have to specify the width for it to be visibly centered. Your #container spans the whole width of the #main_content. That's why it seems not centered,

查看更多
家丑人穷心不美
6楼-- · 2020-01-27 11:23

try this one if this is the output you want:

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

#main_content {
background-color: #2185C5;
margin: 0 auto;
}

#container {
width: 100px;
height: auto;
margin: 0 auto;
padding: 10px;
background: red;
}
查看更多
7楼-- · 2020-01-27 11:25

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

查看更多
登录 后发表回答