<div id="grid" class="grid">
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/500/500"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/600/500"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/700/500"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/500/800"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/1500/500"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/700/900"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/1300/500"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/500/770"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/800/800"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/900/400"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/700/1100"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/600/900"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/550/500"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/600/800"/>
    </div>
  </div>
  <div class="cell">
    <div class="content">
      <img src="https://picsum.photos/900/600"/>
    </div>
  </div>
</div>
<button id="switch">
  Switch Normal/Same Height
</button>
#switch {
  position: fixed;
  top: 10px;
  left: 10px;
  padding: 5px 20px
}

.grid {
  margin: 0 auto;
  width: 60vw;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 5px;
  grid-auto-rows: auto;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.grid--same-height .cell {
  position: relative;
}
.grid--same-height .cell::before {
  content: "";
  display: inline-block;
  padding-bottom: 100%;
}

.grid--same-height .content {
  height: 100%;
  position: absolute;
  margin-top: -100%;
}
document.getElementById( 'switch' ).addEventListener( 'click', () => {
  const root = document.getElementById( 'grid' );
  root.classList.toggle( 'grid--same-height' );
});
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.