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

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

当前回答

我通常的方式是使用绝对的位置:

#inner{
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
  position: absolute;
}

外部迪夫不需要任何额外的属性来工作。

其他回答

如果您不想设置固定宽,并且不需要额外的边界,则将显示器添加到您的元素中: inline-block。

你可以使用:

#element {
    display: table;
    margin: 0 auto;
}

使用下面的代码。

HTML

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

CSS

#outer {
  text-align: center;
}
#inner{
  display: inline-block;
}

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

<!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>
#inner {
    width: 50%;
    margin: 0 auto;
}

另一个解决方案,而无需为其中一个元素设置宽度,是使用CSS 3转换属性。

#outer {
  position: relative;
}

#inner {
  position: absolute;
  left: 50%;

  transform: translateX(-50%);
}

技巧是,翻译X(-50%)将#内部元素置于其自己的宽度的左侧50%。

這裡有一個顯示水平和垂直調整的Fiddle。

更多信息可在Mozilla Developer Network上找到。