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

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

当前回答

#outer { 宽度: 160px; padding: 5px; 边界风格: 固体; 边界宽度: 薄; 显示: 区块; } 内部 { 边界: 自动; 背景颜色: 光蓝; 边界风格: 固体; 边界宽度: 薄; 宽度: 80px; padding: 10px; 文本平衡: 中心; } <div id="outer"> <div id="inner">Foo foo</div> </div>

其他回答

#outer {postion: relative}
#inner {
    width: 100px; 
    height: 40px; 
    position: absolute;
    top: 50%;
    margin-top: -20px; /* Half of your height */
}

它是如此简单。

只需决定你想要给内部Div的宽度,然后使用下面的CSS。

CSS

.inner{
  width: 500px; /* Assumed width */
  margin: 0 auto;
}

您可以使用链接 https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview

.outer{
      display: table;
      width: 100%;
      height: 100%;
}
.inner {
    vertical-align: middle;
}

参考 https://v4-alpha.getbootstrap.com/例子/覆盖/

使用:

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

风格:

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

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

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

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

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