【问题标题】:How can I vertically align the contents of a div to middle? [duplicate]如何将 div 的内容垂直对齐到中间? [复制]
【发布时间】:2020-04-11 05:47:08
【问题描述】:

我尝试使用引导程序 4 类“align-middle”和“align-content-center”使父 div 的内容在中间垂直对齐。但是应用这些类并没有给出我想要的结果。内容仍然位于顶部。

<div class="embed-responsive embed-responsive-1by1" style="background:blue; height:10000px">
  <div class="embed-responsive-item">
    <div style="vertical-align: middle;">
      <span class="h4" style="color:white; font-size: 34px;">The text I want to vertically align in the middle</span></div>
  </div>
</div>

【问题讨论】:

  • 哪个版本的 Bootstrap 以及为什么你没有在演示中包含它。如果您使用了适当的类,请显示 that not working.
  • @Paulie_D 我正在使用 bootstrap 4。你知道如何在演示中包含 bootstrap 库吗?
  • 在 CSS 的 CDN 副本中链接。

标签: html css vertical-alignment


【解决方案1】:

使用纯 CSS,您可以使用 display: flex; align-items: center; 实现此目的

<div class="embed-responsive embed-responsive-1by1" style="background:blue; height:300px; display: flex; align-items: center;">
  <div class="embed-responsive-item">
    <div style="vertical-align: middle;">
      <span class="h4" style="color:white; font-size: 34px;">The text I want to vertically align in the middle</span></div>
  </div>
</div>

在 Bootstrap 4 中,embed-responsive-item 类将添加 position: absolute;,这会破坏布局。删除它并为父级添加row 类,为子级添加col-sm-12 align-self-center。这会起作用的。

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="container">
  <div class="row embed-responsive embed-responsive-1by1" style="height:2000px;border:1px solid gray">
    <div class="col-sm-12 align-self-center">
      <span>.align-self-center</span>
    </div>
  </div>
</div>

【讨论】:

  • 为什么这个答案被否决了?如有错误,请发表评论,以便更正。
猜你喜欢
  • 2016-11-10
  • 2014-03-20
  • 2012-08-07
  • 2016-11-20
  • 2015-04-18
  • 2014-05-23
  • 2019-04-15
  • 1970-01-01
  • 2018-01-11
相关资源
最近更新 更多