Flexbox填充项目而不是边缘

时间:2018-03-20 10:00:03

标签: css flexbox

我有一个像这样的基本flexbox实现



.holder {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  max-width: 500px;
  background: wheat;
}

.col img {
  max-width: 100%;
}

.col {
  width: 20%;
  float: left;
  text-align: center;
}

<div class="holder">
  <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
  <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
  <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
  <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
  <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
  <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
  <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
  <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
  <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
  <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
</div>
&#13;
&#13;
&#13;

我试图在每个项目之间添加一些填充但不在边缘。

Flexbox是最好的解决方案吗?有没有人可以指出我的例子?

2 个答案:

答案 0 :(得分:2)

您可以使用flex-basis 属性,使用calc() 功能设置初始宽度:< / p>

&#13;
&#13;
.holder {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  max-width: 500px;
  background: wheat;
}

.col img {
  max-width: 100%;
}

.col {
  /*width: 20%;*/
  /*float: left; not necessary*/
  flex-basis: calc(20% - 5px);
  text-align: center;
}

/* addition, if desired */
img {
  display: block; /* removes bottom margin/whitespace; "vertical-align: bottom" does the same */
}
&#13;
<div class="holder">
  <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
    <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
    <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
    <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
    <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
    <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
    <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
    <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
      <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
      <div class="col">
    <img src="https://dummyimage.com/600x400/000/fff">
  </div>
  </div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

对于柔性盒子来说非常简单。只需为项目设置正确的宽度,并将容器的justify-content属性设置为space-between。确保项目宽度的总和小于容器宽度的100%。