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

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

当前回答

我已经应用了内线风格到内部 div. 使用此一个:

<div id="outer" style="width:100%">  
    <div id="inner" style="display:table;margin:0 auto;">Foo foo</div>
</div>

其他回答

集中一个未知的高度和宽度的DIV

它与合理的现代浏览器(Firefox,Safari/WebKit,Chrome,Internet & Explorer & 10,Opera等)工作。

.content { 位置: 绝对; 左: 50%; 顶: 50%; 转换: 翻译(-50%, -50%); } <div class="content"> 这与任何内容工作</div>

在 Codepen 或 JSBin 上加入它。

<div id="outer" style="width:100%;margin: 0 auto; text-align: center;"> <div id="inner">Foo foo</div> </div>

此分類上一篇: <div id="outer" style="width:100%"> <div id="inner">Foo foo</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;
}

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

工作例子在这里:

这就是你想要的最短的方式。

JSFIDDLE

#outer {
  margin - top: 100 px;
  height: 500 px; /* you can set whatever you want */
  border: 1 px solid# ccc;
}

#inner {
  border: 1 px solid# f00;
  position: relative;
  top: 50 % ;
  transform: translateY(-50 % );
}