【问题标题】:How to make child content vertically in center as respect to parent container in bootstrap 4如何在引导程序 4 中使子内容相对于父容器垂直居中
【发布时间】:2019-01-30 09:54:04
【问题描述】:

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

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;
     }

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

这里是codepen链接:CodePen

【问题讨论】:

    标签: html css bootstrap-4 vertical-alignment


    【解决方案1】:

    只需将 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>
    

    【讨论】:

      【解决方案2】:

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

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

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

      align-items 是使用 display: flex 时的垂直对齐方式。但是,如果您使用 flex-direction: column,则方向是“旋转”的,因此您将使用 justify-content: center,这通常用于水平对齐。

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

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

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

      【讨论】:

      • 我知道删除 h1 标签会将内容置于中心位置,但我需要根据设计将该标题放置在那里。你有什么解决办法
      • 那么我想我会在你想要居中的内容的顶部和底部使用填充,因为使用 flexbox,#welcome div 内的所有内容都会受到影响。
      猜你喜欢
      • 2019-03-25
      • 1970-01-01
      • 2019-04-15
      • 2018-07-07
      • 2023-03-21
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多