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

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

当前回答

使用 Sass (SCSS合成) 你可以用混合物做到这一点:

与翻译

// Center horizontal mixin
@mixin center-horizontally {
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
}

// Center horizontal class
.center-horizontally {
    @include center-horizontally;
}

在HTML标签中:

<div class="center-horizontally">
    I'm centered!
</div>

请记住添加位置:相对;到母 HTML 元素。


与Flexbox

使用Flex,你可以这样做:

@mixin center-horizontally {
  display: flex;
  justify-content: center;
}

// Center horizontal class
.center-horizontally {
    @include center-horizontally;
}

在HTML标签中:

<div class="center-horizontally">
    <div>I'm centered!</div>
</div>

试试这个CodePen!

其他回答

此分類上一篇: <div id="outer" style="width:100%"> <div id="inner">Foo foo</div> </div>

让它简单!

#outer { 显示: flex; justify-content: center; } <div id="outer"> <div id="inner"> Foo foo</div> </div>

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

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

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

使用:

<style>
  #outer{
    text-align: center;
    width: 100%;
  }
  #inner{
    text-align: center;
  }
</style>

.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>