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

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

当前回答

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

你可以使用:

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

其他回答

CSS 定义内容属性

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

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

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

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。

#centered { 位置: 绝对; 左: 50%; 边缘左: -100px; } <div id="outer" style="width:200px"> <div id="centered"> Foo foo</div> </div>

确保母元素定位,即相对、固定、绝对或粘贴。

如果你不知道你的 div 的宽度,你可以使用 transform:translateX(-50%);而不是负面边界。

使用 CSS calc(),代码可以变得更简单:


.centered {
  width: 200px;
  position: absolute;
  left: calc(50% - 100px);
}

原则仍然是相同的;把项目放在中间,并补偿宽度。

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

<!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.container {
  display: flex;
  justify-content: center; /* For horizontal alignment */
  align-items: center;     /* For vertical alignment   */
}

对于内部<div>,唯一的条件是其高度和宽度不应大于其容器的高度。