You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Flexbox垂直列justify-content-between失效:如何无需指定高度实现间距

如何在Bootstrap中无需指定高度实现垂直内容的justify-content-between对齐?

嘿,这个需求完全可以实现!你现在的问题是第三列需要手动设置高度才能让justify-content-between生效,但其实我们可以利用flex布局的特性,让第三列自动跟着中间列的高度走,不用硬写高度值。

问题根源分析

你原来的父容器用了align-items-center,这个属性会让所有子元素垂直居中,而且第三列的height:72px是固定值,不够灵活。我们需要让父容器的高度由内容最高的中间列来撑开,同时让第三列的高度自动匹配父容器,这样justify-content-between就能正常工作了。

解决方案步骤

  • 移除父容器的align-items-center:这个属性会限制子元素的高度自适应,换成align-items-stretch,它会让所有flex子元素拉伸到和容器内最高元素一样的高度。
  • 去掉第三列的固定高度:删掉第三列的style="height:72px",保留d-flex flex-column justify-content-between即可。

修改后的完整代码

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="d-flex align-items-stretch">
  <div class="col-auto">
    <div>asdqwd</div>
  </div>
  <div class="col d-flex flex-column text-center">
    <div>rgergre</div>
    <div>vs</div>
    <div>rger ergerg</div>
  </div>
  <div class="col-auto d-flex flex-column justify-content-between">
    <div style="height:20px;width:20px;background:red">ewf</div>
    <div style="height:20px;width:20px;background:black">qwd</div>
  </div>
</div>

为什么这样能生效?

align-items-stretch是Bootstrap内置的flex布局类,它会让flex容器的所有子元素自动填充容器的高度,而容器的高度会由内容最多、最高的那个子元素(也就是你的中间列)来决定。这样第三列的高度就和中间列完全一致了,justify-content-between自然就能把两个色块分别推到上下两端,完美实现你要的效果!

内容的提问来源于stack exchange,提问作者user6056556

火山引擎 最新活动