Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Similar to this question, I want to create a perfect square grid, but inside of each grid cell, I want to place an image with 100% height.

The problem is because I did the padding-bottom: 100%; height: 0 hack, height: 100% no longer works on the image because the browser thinks the container has 0 height.

How can I set the height of the image to match that of the cell?

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  grid-gap: 4px;
}

.item {
  overflow: hidden;
  position: relative;
  background-color: red;
  width: 100%;
  padding-bottom: 100%;
  height: 0;
}

img {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  display: block;
  /*height: 100%;*/
}
<div class="grid">
  <div class="item">
    <img src="https://picsum.photos/400/300">
  </div>
  <div class="item">
    <img src="https://picsum.photos/300/300">
  </div>
  <div class="item">
    <img src="https://picsum.photos/500/250">
  </div>
  <div class="item">
    <img src="https://picsum.photos/600/300">
  </div>
  <div class="item">
    <img src="https://picsum.photos/300/400">
  </div>
  <div class="item">
    <img src="https://picsum.photos/300/300">
  </div>
  <div class="item">
    <img src="https://picsum.photos/300/300">
  </div>
  <div class="item">
    <img src="https://picsum.photos/300/300">
  </div>
  <div class="item">
    <img src="https://picsum.photos/300/300">
  </div>
  <div class="item">
    <img src="https://picsum.photos/300/300">
  </div>
</div>
question from:https://stackoverflow.com/questions/65649642/square-css-grid-with-square-images

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
275 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could create a "hidden" cell with a pseudo element (width:0px; height: 0px; padding-bottom: 100%;), overlap it with the real first cell and set all cells to the same height with grid-auto-rows: 1fr; and make the images absolutely positioned.

More in this article: https://medium.com/cloudaper/how-to-create-a-flexible-square-grid-with-css-grid-layout-ea48baf038f3

.grid::before {
  content: '';
  width: 0;
  padding-bottom: 100%;
  grid-row: 1 / 1;
  grid-column: 1 / 1;
}
.grid > *:first-child {
  grid-row: 1 / 1;
  grid-column: 1 / 1;
}
.item {
  overflow: hidden;
  position: relative;
  background-color: red;
  width: 100%;
  /* padding-bottom: 100%; */
  /* height: 0; */
}
img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  min-width: 100%;
  min-height: 100%;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...