bootstrap 4 中如何使子内容相对于父容器垂直居中

How to make child content vertically in center as respect to parent container in bootstrap 4

我一直在尝试让我的子内容按照父容器垂直居中。但是子容器总是相对于父容器的。下面是我试过的代码:

HTML

<section id="welcome" class="bg-primary d-flex flex-column">
        <h1>Positions</h1>
        <div class="container text-center my-auto">
           Centered content
        </div>
     </section>

CSS

      #welcome{
        min-height:150px;
        width: 200px;
     }

我正在寻找的是使居中内容文本按照整个部分垂直居中。

这是代码笔link:CodePen

您的 h1 元素导致它未对齐。如果你摆脱它(只是为了测试),你会看到居中的内容移动到中心。

display: flex; 适用于所有直接子元素,因此您要对齐到 h1 和 #welcome 元素的总高度。要在高方形的中心放置居中内容,您可以应用您在#welcome to .my-auto:

上的一些样式
.my-auto {
  min-height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: blue;
}

align-items 是在使用 display: flex 时垂直对齐。但是,如果你使用flex-direction:column,方向是"rotated",那么你会使用justify-content:center,这通常是为了水平对齐。

另一种方法是在要居中的内容的顶部和底部使用填充:

.my-auto {
  padding: 50px 0; /* 50px is an arbitrary number, just to demonstrate */
}

请注意,这会导致居中内容将所有其他元素垂直推离它。

只需使 h1 position-absolute 将其从 DOM...

中的相对定位中移除

https://codepen.io/anon/pen/EeVXbe

<section id="welcome" class="bg-primary d-flex flex-column">
      <h1 class="position-absolute">Positions</h1>
      <div class="container text-center my-auto">
           Centered content
      </div>
</section>