How do you make a layout with CSS where images are added between two columns and it switches every time a column has four images in it

Viewed 37

The page currently fits four images in the horizontal direction, if more images are added in this direction you can scroll to see them. The images should also remain the same size no matter how many other images are on the page.

The html setup is as follows:

<div className="wrapper">
    <img className="item" />
    <img className="item" />
    <img className="item" />
    <img className="item" />
    .
    .
    .
</div>

The expected behaviour of the page as images are dynamically added to the page in order of the number written.

Three images:

[1 2 3]
[]

Five images: (Note: Screen is now filled to the max in horizontal direction):

[1 2 3 4]
[5]

Nine images:

[1 2 3 4 9]
[5 6 7 8]

Thirteen images:

[1 2 3 4 9 10 11 12]
[5 6 7 8 13]

Fixing it for three and five images was not a problem, but when trying to achieve the intended behaviour for nine images it starts becoming hard... Would appreciate all help. I preferably would not want to change the html, unless it makes it much easier to fix.

1 Answers

This is only possible if you wrap your images into groups of four. If you do that, CSS Flexbox can do the rest.

body {
  margin: 0;
}

.wrapper {
  height: 120px;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

.group {
  width: 400px;
  display: flex;
}

.item {
  width: 100px;
  height: 60px;
  background: linear-gradient(45deg, #eee, #bbb);
}
<div class="wrapper">
  <div class="group">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
  </div>
  <div class="group">
    <div class="item">5</div>
    <div class="item">6</div>
    <div class="item">7</div>
    <div class="item">8</div>
  </div>
  <div class="group">
    <div class="item">9</div>
    <div class="item">10</div>
    <div class="item">11</div>
    <div class="item">12</div>
  </div>
  <div class="group">
    <div class="item">13</div>
  </div>
</div>

Related