Flexbox图像网格填充整个宽度并包裹

时间:2017-03-25 04:11:56

标签: html css flexbox

我正在尝试创建一个填充整个空间的图像网格 - 这些图像是随机大小的。我的第一个例子中有一个基本版本。

但是我需要添加更多功能,并将这些图像包装到div中。我无法让它发挥作用。您可以查看第二个示例。

这是一个小提琴:https://jsfiddle.net/v1swdLgt/

您对我如何解决这个问题有任何想法吗?

谢谢!

<div class="thatworks grid">
  <img src="https://unsplash.it/40/30?random" alt="something"/>
  <img src="https://unsplash.it/35/30?random" alt="something"/>
  <img src="https://unsplash.it/42/30?random" alt="something"/>
  <img src="https://unsplash.it/31/30?random" alt="something"/>
  <img src="https://unsplash.it/44/30?random" alt="something"/>
  <img src="https://unsplash.it/32/30?random" alt="something"/>
  <img src="https://unsplash.it/22/30?random" alt="something"/>
  <img src="https://unsplash.it/40/30?random" alt="something"/>
  <img src="https://unsplash.it/35/30?random" alt="something"/>
  <img src="https://unsplash.it/42/30?random" alt="something"/>
  <img src="https://unsplash.it/31/30?random" alt="something"/>
  <img src="https://unsplash.it/44/30?random" alt="something"/>
  <img src="https://unsplash.it/32/30?random" alt="something"/>
  <img src="https://unsplash.it/22/30?random" alt="something"/>
  <img src="https://unsplash.it/42/30?random" alt="something"/>
  <img src="https://unsplash.it/31/30?random" alt="something"/>
  <img src="https://unsplash.it/44/30?random" alt="something"/>
  <img src="https://unsplash.it/32/30?random" alt="something"/>
  <img src="https://unsplash.it/22/30?random" alt="something"/>
</div>

<div class="doesntworks grid">
  <div>
    <img src="https://unsplash.it/40/30?random" alt="something"/> 
  </div>
  <div>
    <img src="https://unsplash.it/35/30?random" alt="something"/>
  </div>
  <div>
   <img src="https://unsplash.it/42/30?random" alt="something"/> 
  </div>
  <div>
    <img src="https://unsplash.it/31/30?random" alt="something"/>
  </div>
  <div>
    <img src="https://unsplash.it/44/30?random" alt="something"/>
  </div>
  <div>
    <img src="https://unsplash.it/32/30?random" alt="something"/>
  </div>
  <div>
    <img src="https://unsplash.it/22/30?random" alt="something"/>
  </div>
  <div>
    <img src="https://unsplash.it/40/30?random" alt="something"/>
  </div>
  <div>
    <img src="https://unsplash.it/35/30?random" alt="something"/>
  </div>
  <div>
    <img src="https://unsplash.it/42/30?random" alt="something"/>
  </div>
</div>


.grid {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 300px;
  border: 2px solid black;
  margin-bottom: 30px;
}

.thatworks img {
  flex: 1;
}

.doesntworks div {
  flex: 1;
}

1 个答案:

答案 0 :(得分:2)

只需将display: flex添加到您的div,并将相同的样式添加到您在工作网格中添加的img

CSS

.thatworks img, .doesntworks img {
    flex: 1;
}
.doesntworks div {
    flex: 1;
    display: flex;
}

样本

https://jsfiddle.net/v1swdLgt/1/