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

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

当前回答

让它简单!

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

其他回答

如果您不想设置固定宽,并且不需要额外的边界,则将显示器添加到您的元素中: inline-block。

你可以使用:

#element {
    display: table;
    margin: 0 auto;
}

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

我已经看到很多和很多答案,他们都是过时的,谷歌已经实施了一个解决这个常见的问题,它将对象的中心字面上在中间,无论发生什么,是的,它是响应性的。

.HTML

...
<div class="parent">
   <form> ... </form>
   <div> ... </div>
</div>

饰 CSS

.parent {
   display: grid;
   place-items: center;
}

这对我工作:

#inner {
    position: absolute;
    margin: 0 auto;
    left: 0;
    width: 7%;
    right: 0;
}

在此代码中,您将确定元素的宽度。

使用 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!