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

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

当前回答

.outer { 背景颜色: rgb(230,230,255); 宽度: 100%; 高度: 50px; }.inner { 背景颜色: rgb(200,200,255); 宽度: 50%; 高度: 50px; 边界: 0 auto; } <div class="outer"> <div class="inner"> 边界 0 auto </div> </div>

其他回答

#inter { 边界: 0.05em 固体黑色; } #outer { 边界: 0.05em 固体红色; 宽度:100%; 显示: flex; justify-content: center; } <div id="outer"> <div id="inner"> Foo foo</div> </div>


其他解决方案

您可以将此 CSS 应用到内部 <div>:

#inner {
  width: 50%;
  margin: 0 auto;
}

当然,你不需要设置宽度为50%,任何宽度低于含有<div>的将工作。

如果您正在针对 Internet Explorer 8 (及以后),可能更好地拥有此相反:

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

它将使内部元素的中心垂直,它工作而不设置特定的宽度。

工作例子在这里:

使用:

<div id="parent">
  <div class="child"></div>
</div>

风格:

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

如果你想把它集中在水平上,你应该写下如下:

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

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

垂直调整到CSS中中心:

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

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

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

我认为这将是一个解决方案:

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

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

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

您可以使用链接 https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview

.outer{
      display: table;
      width: 100%;
      height: 100%;
}
.inner {
    vertical-align: middle;
}

参考 https://v4-alpha.getbootstrap.com/例子/覆盖/