【问题标题】:Auto vertical spacing between random number of elements to fill parent height随机元素之间的自动垂直间距以填充父高度
【发布时间】:2016-05-18 15:13:46
【问题描述】:

我正在寻找一种方法来自动填充 div 中 p 个元素之间的空间,以便每个元素等距分布,第一个元素位于上边距,最后一个位于下边距。

这是一个 jsfiddle 示例:https://jsfiddle.net/5b7am7qu/

<div>
  <p>1</p>
  <p>2</p>
  <p>3</p>
</div>

比如说div被设置了高度,第一段怎么可能在上边距,下段在下边距,然后每个其他p元素之间的垂直间距是等距的。

我不能给每个段落一个 ID 或类,但可以在父级上定义第一个/最后一个子级。

【问题讨论】:

标签: html css flexbox


【解决方案1】:

您可以为每个p 设置一个顶部和底部边距,以确保它们的上下具有相同的空间。您无需区分 :first-child:last-child,因为边距会为所有段落元素自动生成。

.container {
  width: 500px;
  margin: 15px auto;
}
.container div {
  display: table-cell;
  padding: 5px;
}
.left {
  width: 60%;
  background-color: red;
}
.right {
  width: 40%;
  background-color: green;
}
p {
  margin: 10px 0;
}
<div class="container">
  <div class="left">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </div>
  <div class="right">
    <p>
      Paragraph 1
    </p>
    <p>
      Paragraph 2
    </p>
    <p>
      Paragraph 3
    </p>
  </div>
</div>

【讨论】:

    【解决方案2】:

    您可以使用带有justify-content: space-between;flex-direction: column; FiddleFlexbox 来做到这一点

    .right {
      display: flex;
      border: 1px solid black;
      margin: 5px;
      width: 40%;
      height: 200px;
      flex-direction: column;
      justify-content: space-between;
    }
    
    p {
      margin: 0;
    }
    <div class="right">
      <p>Paragraph 1</p>
      <p>Paragraph 2</p>
      <p>Paragraph 3</p>
    </div>

    【讨论】:

    • 我认为您可以编辑您的答案并删除左右部分以阐明 flex 的最小使用,因为 OP 可能是新手
    • 完美,这就是答案,我在使用 flexbox 时遇到了问题,但我缺少的是 justify-content。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 2010-10-08
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多