【问题标题】:Aligning items within a Bootstrap 4 .card using Flexbox使用 Flexbox 在 Bootstrap 4 .card 中对齐项目
【发布时间】:2017-12-16 21:37:08
【问题描述】:

我正在使用 Bootstrap 4,并且有一个带有 card 类的 div,它具有固定的高度。这就是我想要得到的:

我使用的代码是

<div class="card">
    <div class="card-block d-flex flex-column">
        <h2 class="card-title h4 align-self-start">Top Left</h2>
        <div class="align-self-center">
            Middle Middle
        </div>
        <aside class="align-self-end">Bottom Right</aside>
    </div>
</div>

但是这些线条都被挤在一起了,大概是因为card-block 没有扩展到card 的全高。

有没有办法让card-block 填充card,或者让它正确显示?

【问题讨论】:

    标签: flexbox bootstrap-4


    【解决方案1】:

    您可以在card-block 上使用justify-content-between..

    <div class="card">
        <div class="card-block d-flex flex-column">
            <h2 class="card-title h6 align-self-start flex-grow d-flex">Top Left<br>Top Left</h2>
            <div class="align-self-center flex-grow d-flex">
                Middle Middle
            </div>
            <aside class="align-self-end flex-grow d-flex align-items-end">Bottom Right</aside>
        </div>
    </div>
    
    .flex-grow {
        flex: 1 0 0;
    }
    

    演示:https://www.codeply.com/go/5dIgA0ul2q

    更新 2018 Bootstrap 4(稳定版) card-block 现在是 card-body

    【讨论】:

    • 谢谢——这种方法有效,但中间的线在卡片中并不完全居中,因为 h2 比旁边高。有没有办法让中间线始终位于卡片的中心,而不管其他两条线是什么?
    • 我认为你必须让子项目也弯曲,然后使用 flex-grow 让它们填充相等的空间。我更新了代码和演示。
    • 恐怕仍然没有正确居中 - 在高度为 253 像素的卡片上,我看到中间项目下方有 135 像素的空间,而上方只有 104 像素。这两个值应该相等,给定或取 1px — 目前它明显偏离中心。
    • 我已将 side 的 line-height 设置为与 h2 的 line-height 相等,这是一个 hack,但至少会产生看起来正确的东西。不过,有兴趣找到更通用的解决方案。 (有一天,CSS 中的垂直居中实际上会很容易:)
    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 2019-02-21
    • 2021-03-18
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多