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

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

当前回答

我在各个项目中使用的最好是

<div class="outer">
    <div class="inner"></div>
</div>
.outer{
  width: 500px;
  height: 500px;
  position: relative;
  background: yellow;
}
.inner{
  width: 100px;
  height: 100px;
  background:red;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

Fiddle 链接

其他回答

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

垂直调整到CSS中中心:

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

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

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

CSS 3的盒子相匹配属性

#outer {
    width: 100%;
    height: 100%;
    display: box;
    box-orient: horizontal;
    box-pack: center;
    box-align: center;
}

这个方法也很好地工作:

div.container {
  display: flex;
  justify-content: center; /* For horizontal alignment */
  align-items: center;     /* For vertical alignment   */
}

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

我知道我稍晚回答这个问题,我没有打扰阅读每一个答案,所以这可能是一个重复。

inner { width: 50%; background-color: Khaki; margin: 0 auto; }

是的,这是一个短暂而干净的水平调整代码。

.classname {
   display: box;
   margin: 0 auto;
   width: 500px /* Width set as per your requirement. */;
}