我如何用CSS垂直集中一个 <div> 在另一个 <div> 中?

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

当前回答

我知道我稍晚回答这个问题,我没有打扰阅读每一个答案,所以这可能是一个重复。

inner { width: 50%; background-color: Khaki; margin: 0 auto; }

其他回答

我只是使用最简单的解决方案,但它在所有浏览器工作:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>center a div within a div?</title>
        <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }

            #outer{
                width: 80%;
                height: 500px;
                background-color: #003;
                margin: 0 auto;
            }

            #outer p{
                color: #FFF;
                text-align: center;
            }

            #inner{
                background-color: #901;
                width: 50%;
                height: 100px;
                margin: 0 auto;

            }

            #inner p{
                color: #FFF;
                text-align: center;
            }
        </style>
    </head>

    <body>
        <div id="outer"><p>this is the outer div</p>
            <div id="inner">
                <p>this is the inner div</p>
            </div>
        </div>
    </body>
</html>

最好的方法是使用CSS3。

旧盒子模型(重定向)

显示:盒子和其属性盒子包、盒子平行、盒子东方、盒子方向等已被 flexbox 替换,虽然它们可能仍然工作,但不建议在生产中使用。

#outer { 宽度: 100%; /* Firefox */ 显示: -moz-box; -moz-box-pack:中心; -moz-box-align:中心; /* Safari 和 Chrome */ 显示: -webkit-box; -webkit-box-pack:中心; -webkit-box-align:中心; /* W3C */ 显示: 盒子; 盒子包:中心; 盒子包:中心; } #inner { 宽度: 50%; } <div id="outer"> <div id="inner">Foo foo</div> </div>

根据您的可用性,您也可以使用盒子方向、盒子灵活、盒子方向特性。

现代盒子模型与Flexbox

#outer {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}

阅读更多关于专注于儿童元素

链接2 链接3 链接4

这解释了为什么盒子模型是最好的方法:

為什麼W3C盒子模型被認為更好?

此分類上一篇: <div id="outer" style="width:100%"> <div id="inner">Foo foo</div> </div>

div{
    width: 100px;
    height: 100px;
    margin: 0 auto;
}

通常情况下,如果您正在使用DIV静态方式。

如果你想要一个Div集中在Div是绝对的父母,这里是例子:

.parentdiv{
    position: relative;
    height: 500px;
}

.child_div{
   position: absolute;
   height: 200px;
   width: 500px;
   left: 0;
   right: 0;
   margin: 0 auto;
}

这是一个垂直中心的最佳例子 <div>

<!DOCTYPE html> <html> <head> </head> <body> <div id="outer"> <div id="inner">Foo foo</div> </div> </body>