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

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

当前回答

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

其他回答

如果你知道它的宽度,让我们说它是1200像素,去:

.container {
    width:1200px;
    margin-left: calc(50% - 600px);
}

因此,基本上它将添加50%的左边边,低于已知宽的一半。

只需将此 CSS 内容添加到您的 CSS 文件中,它将自动集中内容。

垂直调整到CSS中中心:

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

垂直 + 垂直到中心在 CSS 中:

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

您可以使用显示器: flex 为您的外部 div 和到水平中心 您必须添加 justify 内容: 中心

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

或者您可以参观w3schools - CSS flex Property 更多想法。

中心一个Div在一个Div

.outer { 显示: -webkit-flex; 显示: flex; //-webkit-justify-content: center; //justify-content: center; //align-items: center; width: 100%; height: 100px; background-color: lightgrey; }.inner { 背景颜色: cornflowerblue; padding: 2rem; margin: auto; //align-self: center; } <div class="outer"> <div class="inner"

您可以添加另一个具有相同尺寸的Div,并将其移动到左侧 -50%(半宽的Div)和50%的Div。

此分類上一篇: <div id="outer"> <div id="inner"><div>Foo foo</div></div> </div>