2

I have this html...

<div class="img-panel">
    <img src="src.png" alt="image" class="img">
    <img src="src.png" alt="image" class="img">
    <img src="src.png" alt="image" class="img img--high">
    <!-- ... -->
</div>

... And this css...

.img-panel {
    height: 60vh;
    width: 95vw;
    overflow-y: scroll;
    overflow-x: hidden;
    display: flex;
    padding: 0 1vw;
    justify-content: start;
    flex-wrap: wrap;
    align-content: start;
}

.img {
    width: 18vw;
    border-radius: 1vmin;
    margin: 1vh 0.5vw;

    height: 8vh;
    border: 1px solid black;
}

.img--high {
    height: 18vh;
}

I'd like to remove the gaps when wrapping and make the images flow to the bottom of each other so that instead of having this, I have something like this.

Is there a way to achieve that using just css?

Edgar TA
  • 49
  • 1
  • 5

1 Answers1

0

This functionality used to require Javascript using libraries like Packery but with css grid you can accomplish it without Javascript (See snippet below). It's is not quite as good a Javascript assisted layout like Packery but it will do in a pinch.

This article has good insight into masonry with css https://www.smashingmagazine.com/native-css-masonry-layout-css-grid/

body {
  background-color: white;
}

.container {
  column-count: 4;
  column-gap: 12px;
}
img {
  max-width: 100%;
}

.container div {
  display: grid;
  break-inside: avoid;
  grid-template-rows: 1fr auto;
  margin: 0 0 12px 0;
}

.container div > img {
  grid-row: 1 / -1;
  grid-column: 1;
}
<div class="container">
  <div>
    <img src="https://i.stack.imgur.com/B8MuG.jpg" alt="" />
  </div>
  <div>
    <img src="https://i.stack.imgur.com/QZMCE.jpg" alt="" />
  </div>
  <div>
    <img src="https://i.stack.imgur.com/ICHPf.jpg" alt="" />
  </div>
  <div>
    <img src="https://i.stack.imgur.com/lMyFl.jpg" alt="" />
  </div>
  <div>
    <img src="https://i.stack.imgur.com/fcUfF.jpg" alt="" />
  </div>
  <div>
    <img src="https://i.stack.imgur.com/B8MuG.jpg" alt="" />
  </div>
  <div>
    <img src="https://i.stack.imgur.com/ICHPf.jpg" alt="dog" />
  </div>
  <div>
    <img src="https://i.stack.imgur.com/B8MuG.jpg" alt="bunny" />
  </div>

</div>
Authentic Science
  • 838
  • 1
  • 3
  • 5