我如何用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!

其他回答

可以使用 CSS 3 Flexbox. 在使用 Flexbox 时,您有两种方法。

设置主显示:flex; 并将属性 {justify-content:center;,align-items:center;} 添加到您的主元素。

#outer { 显示: flex; justify-content: center; align-items: center; } <div id="outer" style="width:100%"> <div id="inner">Foo foo</div> </div>

设置父母显示:flex 并将 margin:auto 添加到孩子身上。

#outer { 显示: flex; } #inner { margin: auto; } <div id="outer" style="width:100%"> <div id="inner">Foo foo</div> </div>

回归2022

这是一个非常古老的问题,所以我只是试图报告今天的情况:

CSS 网络和 flexbox 是您对中心、水平或垂直的最佳选项; margin:auto 方法工作得好,如果内部内容不是一个盒子(内线区块是好的); margin 50% 与 transform:translateX(50%) 是粗糙的力量,但工作得好; 与绝对的位置和 translateX/Y 也适用于水平和垂直的中心,许多对话使用它,扩展高度

这就是2022年的样子,我希望我们永远不会需要更多的网和 flexbox。

添加文本:中心;到 parent div

#outer {
    text-align: center;
}

HTTPS://jsfiddle.net/7qwxx9rs/

#outer > div {
    margin: auto;
    width: 100px;
}

HTTPS://jsfiddle.net/f8su1fLz/

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

#inter { 边界: 0.05em 固体黑色; } #outer { 边界: 0.05em 固体红色; 宽度:100%; 显示: flex; justify-content: center; } <div id="outer"> <div id="inner"> Foo foo</div> </div>


其他解决方案

您可以将此 CSS 应用到内部 <div>:

#inner {
  width: 50%;
  margin: 0 auto;
}

当然,你不需要设置宽度为50%,任何宽度低于含有<div>的将工作。

如果您正在针对 Internet Explorer 8 (及以后),可能更好地拥有此相反:

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

它将使内部元素的中心垂直,它工作而不设置特定的宽度。

工作例子在这里: