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

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

当前回答

中心一个元素,不需要动态高度和宽度的旋转器/父母

没有副作用:它不会限制一个集中元素的宽度低于视门宽度,当使用Flexbox中的边缘在一个集中元素内

position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%));

垂直 + 垂直中心,如果其高度与宽度相同:

position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));

其他回答

我创建了这个例子,以表明如何垂直和水平地调整。

这个代码基本上就是这样:

#outer {
 position: relative;
}

和...

#inner {
  margin: auto;
  position: absolute;
  left:0;
  right: 0;
  top: 0;
  bottom: 0;
}

它会留在中心,即使你重新启动屏幕。

它也可以用绝对定位来垂直和垂直集中,如下:

#outer{
    position: relative;
}

#inner{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%)
}

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

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 % );
}

#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

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

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

在 Codepen 或 JSBin 上加入它。