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

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

当前回答

您可以添加此代码:

#inner { 宽度: 90%; margin: 0 auto; text-align:center; } <div id="outer"> <div id="inner"> Foo foo</div> </div>

其他回答

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

下面是一个例子:

<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之后,并为内部Div(与桌面细胞显示器)设置垂直调整,并在Div或页面中心的内部Div中使用的每个标签。

注意:您必须将指定的高度设置到外面

它是最好的方式你知道没有位置相对或绝对,你可以使用它在每个浏览器一样。

#outer{ 显示: 表; 高度: 100vh; 宽度: 100%; } #inner{ 显示: 表细胞; 垂直平衡: 中间; 文本平衡: 中心; } <div id="outer"> <div id="inner"> <h1> 设置内容中心 </h1> <div> hi 这是最适合您的项目中心 </div> </div> </div> </div>

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

添加文本:中心;到 parent div

#outer {
    text-align: center;
}

HTTPS://jsfiddle.net/7qwxx9rs/

#outer > div {
    margin: auto;
    width: 100px;
}

HTTPS://jsfiddle.net/f8su1fLz/