css grid equal height for each element keeping responsivness

I have the grid, each element has an image and other divs underneath. Because it’s a grid, each element has responsive width and so it scales automatically as the screen shrinks. I would like the images (which can have different sizes and not be homogeneous) of the elements to have the same height while maintaining this responsive feature. If I set a specific height, as the screen shrinks the aspect ratio is not maintained. Basically I need a youtube style responsivness, that is a perfect example. How can I do it?

This is my grid:

JSX:

<div className="home-container">
  {elements.map((el) => (
    <Element el={el}></Element >
  ))}
</div>

CSS:

.home-container {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 20px;
  margin-left: 250px;
  grid-auto-rows: 1fr;
  grid-row-gap: 30px;
}

This is my elementcard:

JSX:

<div className="element-container">
   <div className="element-img">
      <img src={imageUrl} alt={title} />
   </div>
   <div>...</div>
   <div>...</div>
</div>

CSS:

.element-container {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  height: fit-content;
  border-radius: 10px;
  overflow: hidden;
}

.element-img {
  display: flex;
  margin-bottom: 20px;
}

.element-img > img {
  width: 100%;
  height: 100%;
  border-radius: 20px;
  object-fit: cover;
}

PROBLEM:
As you can see, the dish problem is ok when the grid is not shrunk, but then that it does not maintain the same aspect-ratio as the other elements.

enter image description here

  • stackoverflow.com/questions/56711501/…

    – 

To Make equal-height columns with CSS grid, set all grid items in a row to the height of the tallest column with the grid-auto-rows: 1fr; rule. To make columns all the same width, use the grid-template-columns: 1fr 1fr 1fr; rule and use the same number of fractional values as the number of columns.

In HTML Code:

<div class="grid">
    <div>A</div>
    <div>A<br>B<br>C</div>
    <div>A<br>B</div> 
</div>

The CSS rules:

.grid {
    display: grid;
    grid-auto-rows: 1fr;
    grid-template-columns: 1fr 1fr 1fr;
}

.grid > div:nth-child(1) {
    background-color: #f97171;
}
.grid > div:nth-child(2) {
    background-color: #f99e50;
}
.grid > div:nth-child(3) {
    background-color: #f5d55f;
}

Leave a Comment