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

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

当前回答

我找到了类似的路径与边缘左,但它也可以留下。

#inner {
    width: 100%;
    max-width: 65px; /* To adapt to screen width. It can be whatever you want. */
    left: 65px; /* This has to be approximately the same as the max-width. */
}

其他回答

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

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

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

使用:

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

风格:

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

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

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

这个方法也很好地工作:

div.container {
  display: flex;
  justify-content: center; /* For horizontal alignment */
  align-items: center;     /* For vertical alignment   */
}

对于内部<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!

根据您的情况,最简单的解决方案可能是:

margin: 0 auto; float: none;