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

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

当前回答

你可以做这样的事情

#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;
}

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

其他回答

<!DOCTYPE html> <html> <head> <title>Center</title> <style>.outer{ 文本平衡:中心; }.inner{ 宽度: 500px; 边界: 0 自动; 背景: 棕色; 颜色: 红色; } </style> </head> <body> <div class="outer"> <div class="inner"> 此 DIV 是中心的</div> </div> </body>

请尝试一下,它将工作没有HTML中心标签。

给内部 div 一些宽度,并添加 margin:0 auto; 在 CSS 属性中。

试着和周围玩

margin: 0 auto;

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

text-align: center;

这个方法也很好地工作:

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

对于内部<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;
}

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

工作例子在这里: