3列布局中3 * n项之间的等填充?

时间:2017-11-25 17:20:30

标签: css padding

我想使用flex属性实现3列布局,如下所示:

item-----item-----item

-----表示每个项目之间的填充。现在,问题在于这些规则:

.col-3-grid .grid-item {
    padding: 0 10px 0 0;
}

.col-3-grid .grid-item:nth-of-type(2n) {
    padding: 0 5px 0 5px;
}

.col-3-grid .grid-item:nth-of-type(3n) {
    padding: 0 0 0 10px;
}

为布局的第一行工作,如果我有5个.grid-item或4个,甚至超过3个,它会断开,看起来像这样:

item--item-----item

空间不均匀,因为我的规则无法获取“好的,它是行的结束,重置规则”,因为它将.col-3-grid .grid-item:nth-of-type(2n)规则应用于我的4th项目,根据代码,它是一个正常的设备。

但我怎么能告诉它应用正确的填充?

1 个答案:

答案 0 :(得分:1)

由于您使用的是弹性框,我建议您使用justify-content: space-between属性。它将自行调整任意数量的.grid-items

.col-3-grid,
.col-4-grid,
.col-5-grid {
  width: 100vw;
  height: 20vh;
  background: #ccc;
  display: flex;
  justify-content: space-between;
}

.grid-item {
  width: 15vw;
  height: 100%;
  background: #000;
  color: #fff;
}
<div class="col-3-grid">
  <div class="grid-item">Block1</div>
  <div class="grid-item">Block2</div>
  <div class="grid-item">Block3</div>
</div>
<br>
<div class="col-4-grid">
  <div class="grid-item">Block1</div>
  <div class="grid-item">Block2</div>
  <div class="grid-item">Block3</div>
  <div class="grid-item">Block4</div>
</div>
<br>
<div class="col-5-grid">
  <div class="grid-item">Block1</div>
  <div class="grid-item">Block2</div>
  <div class="grid-item">Block3</div>
  <div class="grid-item">Block4</div>
  <div class="grid-item">Block5</div>
</div>