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

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

当前回答

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

其他回答

CSS 定义内容属性

它将Flexbox元件调整到容器的中心:

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

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

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

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

在 Codepen 或 JSBin 上加入它。

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

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

#outer {
 position: relative;
}

和...

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

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

你可以做这样的事情

#container {
   display: table;
   width: <width of your container>;
   height: <height of your container>;
}

#inner {
   width: <width of your center div>;
   display: table-cell;
   margin: 0 auto;
   text-align: center;
   vertical-align: middle;
}

這也會垂直調整 #內部. 如果你不願意,移除顯示器和垂直調整的特性;

试着和周围玩

margin: 0 auto;

如果你也想集中你的文本,试着使用:

text-align: center;