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

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

当前回答

我最近找到了一个方法:

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

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

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

其他回答

方法1:使用边缘财产

如果元素不是区块级元素,然后添加显示器:区块属性到它。

#outer { 显示: flex; justify- 内容: 中心; 背景颜色: 银色; } #inner { 背景颜色: #f07878; } <div id="outer"> <div id="inner"> Foo foo</div> </div>

这是一个经典的方法,以中心元素. 设置位置:相对外部元素. 设置内部元素的位置为绝对和左: 50%. 这将推动内部元素从外部元素的中心开始. 现在使用转变属性和设置转变: 翻译X(-50%) 这将使元素的中心水平。

您可以使用一行代码,仅仅是文本同步:中心。

下面是一个例子:

<div id="outer" style="width:100%"> <div id="inner"><button>hello</button></div> </div>

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

<!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>

例如,请参见此链接和下面的剪辑:

div#outer { 高度: 120px; 背景颜色: 红色; } div#内部 { 宽度: 50%; 高度: 100%; 背景颜色: 绿色; 边缘: 0 自动; 文本平衡: 中心; /* 文本平衡到中心垂直. */ 线高度: 120px; /* 文本平衡到中心垂直。

如果你有很多孩子在一个父母之下,那么你的CSS内容应该像这个例子。

HTML 内容看起来喜欢此:

<div id="outer" style="width:100%;">
    <div class="inner"> Foo Text </div>
    <div class="inner"> Foo Text </div>
    <div class="inner"> Foo Text </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> Foo Text </div>
</div>

然后,看看这个例子在Fiddle。

#outer {postion: relative}
#inner {
    width: 100px; 
    height: 40px; 
    position: absolute;
    top: 50%;
    margin-top: -20px; /* Half of your height */
}