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

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

当前回答

你可以以不同的方式做到这一点. 请参见下面的例子:

1. First Method
#outer {
   text-align: center;
   width: 100%;
}
#inner {
   display: inline-block;
}


2. Second method
#outer {
  position: relative;
  overflow: hidden;
}
.centered {
   position: absolute;
   left: 50%;
}

其他回答

.outer { 背景颜色: rgb(230,230,255); 宽度: 100%; 高度: 50px; }.inner { 背景颜色: rgb(200,200,255); 宽度: 50%; 高度: 50px; 边界: 0 auto; } <div class="outer"> <div class="inner"> 边界 0 auto </div> </div>

我只是建议使用正当内容:中心;当容器显示为 flex. 和文本平行:中心;当它是关于文本元素。

点击下面的代码并根据要求修改。

#content_block { 边界: 1px 固体黑色; padding: 10px; 宽度: 50%; 文本平衡:中心; } #container { 边界: 1px 固体红色; 宽度: 100%; padding: 20px; 显示: flex; justify-content: center; } <div id="container"> <div id="content_block"> Foo foo check</div> </div>

如果你知道它的宽度,让我们说它是1200像素,去:

.container {
    width:1200px;
    margin-left: calc(50% - 600px);
}

因此,基本上它将添加50%的左边边,低于已知宽的一半。

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

<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 链接

使用:

<div id="parent">
  <div class="child"></div>
</div>

风格:

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

如果你想把它集中在水平上,你应该写下如下:

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