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

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

当前回答

<center>

我被最简单的中心所知道的混乱了吗?

</center>

其他回答

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

<!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>
#outer {postion: relative}
#inner {
    width: 100px; 
    height: 40px; 
    position: absolute;
    top: 50%;
    margin-top: -20px; /* Half of your height */
}

我最近找到了一个方法:

#outer {
    position: absolute;
    left: 50%;
}

#inner {
    position: relative;
    left: -50%;
}

两个元素必须是相同的宽度,以便正常运作。

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

#outer {
  position: relative;
}

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

  transform: translateX(-50%);
}

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

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

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

设置宽度,并设置边缘向左和边缘向右到自动。 这是仅限于水平,但是. 如果你想要两种方式,你只会做这两种方式. 不要害怕尝试; 它不像你会打破任何东西。