尝试使用 CSS flex 制作方形图像墙,但第一行未按预期运行

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

按照各种在线教程,我正在尝试制作一个仅显示方形裁剪图像的图库。它似乎在第二行和第三行有效,但出于什么原因而不是在第一行?有谁知道我可能做错了什么?

.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>

代码笔: https://codepen.io/pandalism/pen/XWdyJbz

任何方向都将非常感谢!

问题出在 500x750 图片上。根据 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.

您基本上已经使用 gallery-item:before 强制执行了最小高度,但实际确定的唯一尺寸是宽度;如果项目的高度>宽度,则会导致 gallery-item 展开。当您将 500x750 图像放在任何一行时,您会看到它垂直扩展。

我建议将 gallery-item 的样式设置为每个 this answer 的正方形。强制执行最大高度后,contain 应该会像您希望的那样工作。

YOU CAN USE THIS CODE OF HTML IF YOU ONLY WANT TO DISPLAY SQUARE SIZE IMAGES
<html>
<head>
</head>
<div class='article'>
<h1>
title titile title
</h1>
<div class='gallery'>
  
    <img class='gallery-img' width=25% height=50% src='https://via.placeholder.com/500' />
 
   
    <img class='gallery-img' width=25% height=50% src='https://via.placeholder.com/500x750' />
  
  
    <img class='gallery-img' width=25% height=50% src='https://via.placeholder.com/750x500' />
      
    <img class='gallery-img' width=25% height=50% src='https://via.placeholder.com/750x500' />
 
 
    <img class='gallery-img' width=25% height=50% src='https://via.placeholder.com/300x300' />
 
  
    <img class='gallery-img'  width=25% height=50% src='https://via.placeholder.com/750x750' />
 
  
    <img class='gallery-img'  width=25% height=50% src='https://via.placeholder.com/750x750' />
  </div>

</html>