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

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

当前回答

<html>

*{ margin: 0; padding: 0; } #outer{ 背景: 红色; 宽度: 100%; 高度: 100vh; 显示: flex; /*center 垂直*/ 正当内容: 中心; flex 方向: 列; /*center 垂直*/ 匹配元素: 中心; } #inner{ 宽度: 80%; 高度: 40px; 背景: g

其他回答

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

<!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 { 显示: 网; justify- 内容: 中心; } <div id="outer"> <div id="inner">hello</div> </div> 在这里输入代码

最熟悉的方式,它是广泛使用和工作在许多浏览器,包括旧的,是使用边界如下:

#parent { 宽度: 100%; 背景颜色: #CCCCCC; } #child { 宽度: 30%; /* 我们需要宽度 */ 边缘: 0 自动; /* 这是魔法 */ 颜色: #FFFFFF; 背景颜色: #000000; 粘贴: 10px; 文本平衡: 中心; } <div id="parent"> <div id="child"> 我是孩子,我是水平中心! 我的爸爸是一个灰色的 div dude!</div> </div>

运行代码以查看它是如何工作的. 此外,有两个重要的事情你不应该忘记在你的CSS,当你试图以这种方式集中: 边缘: 0 自动;. 这使它是 div 中心,如你想要的。

我最近找到了一个方法:

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

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

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

CSS 定义内容属性

它将Flexbox元件调整到容器的中心:

#outer {
    display: flex;
    justify-content: center;
}