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:16

if you don't wanna set a width for #container just add

text-align: center; 

to #main_content

查看更多
可以哭但决不认输i
3楼-- · 2020-01-27 11:17

You must assign a width to the div you want to center.

Like This:

#container {
    width: 500;
    margin: 0 auto;
    padding: 10px;
}

More information and examples on these links:

http://www.w3schools.com/css/css_align.asp

http://www.w3schools.com/css/tryit.asp?filename=trycss_align_container

查看更多
等我变得足够好
4楼-- · 2020-01-27 11:20

it would work giving the #container div width:80%[any width less than the main content and have given in % so that it manages well from both left and right] and giving margin:0px auto; OR margin:0 auto; [both works fine].

查看更多
Summer. ? 凉城
5楼-- · 2020-01-27 11:20
#main_content {    
    width: 400px; margin: 0 auto;
    min-height: 300px;
    height: auto;
    background-color: #2185C5;
    position: relative;
}

#container {
    width: 50%;
    height: auto;
    margin: 0 auto;background-color: #ccc;
    padding: 10px;
    position: relative;
}

try this tested ok. live check on jsfiddle

查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-01-27 11:20

I have used the following method in few projects

https://jsfiddle.net/u3Ln0hm4/

.cellcenterparent{
  width: 100%;
  height: 100%;
  display: table;
}

.cellcentercontent{
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
查看更多
Juvenile、少年°
7楼-- · 2020-01-27 11:21

Make the css this way...

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

#container {
    height: auto;
    width: 90%;
    margin: 0 auto;
    background-color: #fff;
    padding: 10px;
}

Working example here -> http://jsfiddle.net/golchha21/mjT7t/

查看更多
登录 后发表回答