简体   繁体   English

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

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

I have been trying to make my child content vertically centered as per the parent container. 我一直在尝试根据父容器使我的孩子内容垂直居中。 But the child container is always in relative to parent container. 但是子容器始终相对于父容器。 Below is the code I have tried: 以下是我尝试过的代码:

HTML 的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 的CSS

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

What I am looking is to make Centered Content text vertically centered as per the whole section. 我正在寻找的是使“ 居中内容”文本按照整个部分垂直居中。

Here is the codepen link: CodePen 这是codepen链接: CodePen

Just make h1 position-absolute to remove it from relative positioning within the DOM... 只需将h1 position-absolute设为position-absolute即可将其从DOM中的相对位置中删除...

https://codepen.io/anon/pen/EeVXbe 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>

Your h1 element is what's causing it to mis-align. 您的h1元素是导致其未对齐的原因。 If you get rid of it (just to test) you'll see centered content move to the center. 如果您摆脱它(只是为了测试),您会看到居中的内容移到了中心。

display: flex; 显示:flex; applies to all of that elements direct children, so you're aligning to aggregate height of both the h1 and the #welcome element. 适用于所有直接子元素,因此您要对齐h1和#welcome元素的总高度。 To have Centered Content in the center of a tall square, you could apply some of the styles you have on #welcome to .my-auto: 要将居中的内容放置在一个大正方形的中心,可以将#welcome上的某些样式应用于.my-auto:

.my-auto {
  min-height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: blue;
}

align-items is what does vertical alignment when using display: flex. align-items是使用display:flex时的垂直对齐方式。 However, if you use flex-direction: column, the direction is "rotated", so you would use justify-content: center, which is normally for horizontal alignment. 但是,如果使用flex-direction:列,则方向是“旋转的”,因此您将使用justify-content:center,通常用于水平对齐。

A different approach is to use padding on top and bottom of the content you want to center: 另一种方法是在要居中的内容的顶部和底部使用填充:

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

Note that this will cause centered content to push all other elements vertically away from it. 请注意,这将导致居中的内容将所有其他元素垂直推离它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM