Search code examples
htmlcssimageflexboxgallery

Trying to make a square image wall using CSS flex, but first row doesn't behave as expected


following various online tutorials, I'm trying to make an image gallery which just simply displays square cropped images. It appears to work on the second and third row, but for what ever reason not on the first row? Does anyone know what I might be doing wrong?

.article {
  border: 1px solid red;
  max-width: 1000px;
}

.gallery {
  border: 1px solid blue;
  display: flex;
  flex-wrap: wrap;
}

.gallery-item {
  border: 1px solid red;
  flex-basis: 49%;
}

.gallery-item:before {
  content: "";
  float: left;
  padding-top: 100%;
}

.gallery-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class='article'>
<h1>
title titile title
</h1>
<div class='gallery'>
  <div class='gallery-item'>
    <img class='gallery-img' src='https://via.placeholder.com/500' />
  </div>
  <div class='gallery-item'>
    <img class='gallery-img' src='https://via.placeholder.com/500x750' />
  </div>
  <div class='gallery-item'>
    <img class='gallery-img' src='https://via.placeholder.com/750x500' />
  </div>
  <div class='gallery-item'>
    <img class='gallery-img' src='https://via.placeholder.com/750x500' />
  </div>
  <div class='gallery-item'>
    <img class='gallery-img' src='https://via.placeholder.com/300x300' />
  </div>
  <div class='gallery-item'>
    <img class='gallery-img' src='https://via.placeholder.com/750x750' />
  </div>
  <div class='gallery-item'>
    <img class='gallery-img' src='https://via.placeholder.com/750x750' />
  </div>
</div>
</div>

Codepen: https://codepen.io/pandalism/pen/XWdyJbz

Any direction at all would be great thanks!


Solution

  • The problem is with the 500x750 image. According to the cover documentation:

    The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit.

    You've basically enforced a minimum height using gallery-item:before, but the only dimension that's actually determined is width; if the item has height>width, it will cause the gallery-item to expand. When you put the 500x750 image in any row, you'll see that it expands vertically.

    I'd recommend styling the gallery-item to be a square per this answer. Once you have a maximum height enforced, contain should work like you want it to.