【问题标题】:margin-bottom / vertical space strategy for CSS columns (flex)CSS 列的 margin-bottom / 垂直空间策略(flex)
【发布时间】:2020-06-02 20:50:00
【问题描述】:

场景

顶部的一个部分有两列 (flex)。每列包含多个元素。

下面的一个部分有一个单独的列。

每列中元素之间的垂直间距应为 30px(我们正在考虑 rem 或 em 大小,但在此讨论中我们坚持使用 px)。

部分之间的垂直间距应为 40 像素。 (我在这里选择了一个不同的数字以使其更有趣。)

实施,第一次尝试

第一步是在不同的元素上设置margin-bottom

<style>
.section-top {
  display: flex;
}
.section-top > div {
  width: 50%;
}
.container > section {
  margin-bottom: 40px;
}
.column-left > section,
.column-right > section {
  margin-bottom: 30px;
}
</style>
<div class="container">
  <section class="section-top">
    <!-- top section with two columns (flex) -->
    <div class="column-left">
      <section>Block L1</section>
      <section>Block L2</section>
    </div>
    <div class="column-right">
      <section>Block R1</section>
      <section>Block R2</section>
      <section>Block R3</section>
    </div>
  </section>
  <section class="section-bottom">Section 2</div>
  <section class="section-bottom">Section 3</div>
</div>

问题

现在顶部和底部的可见内容之间有 70 像素的垂直空间。相反,我们只想要 40px。

这并不奇怪,众所周知,弹性项目的垂直边距不会随着容器的边距折叠。

问题

有什么好的常用策略来解决这个问题,并且在顶部和底部之间只有 40 像素而不是 70 像素的空间?

理想情况下应该支持:

  • 每列中元素的数量和高度不同。
  • 可能存在没有元素的列。
  • 列元素与顶级部分的垂直间距不同。
  • 使用嵌套元素的边距中和或折叠。​​
  • 基于组件的 CSS,其中顶级部分之间的边距定义独立于部分内容。

到目前为止我尝试了什么

技术上有很多方法可以解决这个问题:

  • 在每列中将margin-bottom: 0; 设置为:last-child
    • 问题:不消​​除嵌套元素的边距。
  • .section-top 上使用margin-bottom: 0;,而不是在每列或每列内的最后一个子项上使用40px。
    • 问题:需要在两个地方定义40px。例如。如果我想稍后将顶级部分之间的垂直间距更改为 60px,我还需要更新列的 CSS。
  • 使用负边距来补偿?

所有这些都会起作用,但也许还有更好的东西我没有看到。

【问题讨论】:

    标签: css flexbox margin


    【解决方案1】:

    这是一种解决方案。我不知道它是否是最好的,但它对我有用。

    我们在每一列中添加一个::after 伪元素。

    <style>
    .container > section {
      margin-bottom: 40px;
    }
    .section-top {
      display: flex;
    }
    .section-top > .column {
      width: 50%;
    }
    .section-top > .column > section {
      margin-bottom: 30px;
    }
    .section-top > .column::after {
      /* Optionally change these to 40px / -40px, not sure what is better */
      margin-top: 30px;
      margin-bottom: -30px;
    }
    </style>
    <div class="container">
      <section class="section-top">
        <!-- top section with two columns (flex) -->
        <div class="column column-left">
          <section>Block L1</section>
          <section>Block L2</section>
        </div>
        <div class="column column-right">
          <section>Block R1</section>
          <section>Block R2</section>
          <section>Block R3</section>
        </div>
      </section>
      <section class="section-bottom">Section 2</div>
      <section class="section-bottom">Section 3</div>
    </div>
    

    【讨论】:

    • 这是一条死胡同。如果它们在移动设备上垂直堆叠,它会删除列之间的空间。
    猜你喜欢
    • 1970-01-01
    • 2010-09-22
    • 2014-01-23
    • 2021-11-14
    • 2010-09-06
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    相关资源
    最近更新 更多