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

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

当前回答

您可以添加此代码:

#inner { 宽度: 90%; margin: 0 auto; text-align:center; } <div id="outer"> <div id="inner"> Foo foo</div> </div>

其他回答

您可以使用 CSS Flexbox。

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

您可以在此链接中了解更多信息: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

我通常的方式是使用绝对的位置:

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

外部迪夫不需要任何额外的属性来工作。

使用下面的 CSS 内容为 #inner div:

#inner {
  width: 50%;
  margin-left: 25%;
}

我主要使用这个CSS内容为中心Divs。

你可以做这样的事情

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

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

我最近找到了一个方法:

#outer {
    position: absolute;
    left: 50%;
}

#inner {
    position: relative;
    left: -50%;
}

两个元素必须是相同的宽度,以便正常运作。