CSS / Flexboxes:连续定位图像

时间:2017-01-24 20:24:46

标签: html css flexbox

我希望将一堆图像放在彼此旁边(连续4个),将第5行放在下一行......

图像宽度应为行的1/4。

我试图用弹性盒找到解决方案,但没有任何线索......



<h2>Students</h2>
<div class="content">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
.content {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.content > div {
  width: 25%;
  padding: 0 10px 10px 0;
  box-sizing: border-box;
}

.content > div  img {
  width: 100%;
}
&#13;
<h2>Students</h2>
<div class="content">
  <div><img class="student" src="http://placehold.it/400x400"></div>
  <div><img class="student" src="http://placehold.it/400x400"></div>
  <div><img class="student" src="http://placehold.it/400x400"></div>
  <div><img class="student" src="http://placehold.it/400x400"></div>
  <div><img class="student" src="http://placehold.it/400x400"></div>
</div>
&#13;
&#13;
&#13;

这是你想要的吗?

答案 1 :(得分:1)

您可以设置一个静态width,最终设置一个margin,如果您想要连续4次,则不应超过25%,连续三次设置为33.33%,等等。

.content {
  display:flex;
  flex-wrap:wrap;
  align-items:flex-start; /* else image aare stretching in Chrome */
  }
.student {
  margin:1vw 1%;
  width:23%;/* 23% + 1% margin-left + 1% margin-right = 25% */
  }
<h2>Students</h2>
<div class="content">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
</div>

修改 很明显,如果未设置 align-items:flex-start; >,Chrome就会出现问题,

...让我觉得float是这种简单布局的跨浏览器:

.content {
  overflow:hidden;
  }
.student {
  float:left;
  margin: 1%;
  width:23%;/* 23% + 1% margin-left + 1% margin-right = 25% */
  }
<h2>Students</h2>
<div class="content">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
  <img class="student" src="http://placehold.it/400x400">
</div>

只是说:)