csscss-grid

How to constrain a grid's height to match the height of text content, not an oversized image?


I have a CSS grid with two columns: one contains text, and the other contains an image. The problem is that the grid's height is being dictated by the image, which is larger than the text. I want the grid's height to follow the height of the text instead.

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;

  gap: 1em;
}

.image-container img {
  max-height: 100%;
  width: 100%;
  height: auto;
}

.text {
  background: lightblue;
}
<div class="grid">
  <div class="text">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sit amet purus ac nunc.
  </div>
  <div class="image-container">
    <img src="https://primary-test.jwwb.nl/unsplash/vigsqYux_-8.jpg" alt="Example image" />
  </div>
</div>

I could solve this by adding a position absolute to the image, so it is removed from the content flow. But I would think there is something that the grid layout system offers to do this natively. Is there?

Here is solution with position absolute:

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1em;
}

.image-container {
  position: relative;
}

.image-container img {
  position: absolute;
  max-height: 100%;
  width: 100%;
  height: auto;
  object-fit: cover;
}

.text {
  background: lightblue;
}
<div class="grid">
  <div class="text">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sit amet purus ac nunc.
  </div>
  <div class="image-container">
    <img src="https://primary-test.jwwb.nl/unsplash/vigsqYux_-8.jpg" alt="Example image" />
  </div>
</div>


Solution

  • I'm not sure what's non-native about using position: absolute, but one alternative is to use size containment:

    .grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
    
      gap: 1em;
    }
    
    .image-container {
      contain: size;
    }
    
    .image-container img {
      height: 100%;
      width: 100%;
      object-fit: cover;
    }
    
    .text {
      background: lightblue;
    }
    <div class="grid">
      <div class="text">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sit amet purus ac nunc.
      </div>
      <div class="image-container">
        <img src="https://primary-test.jwwb.nl/unsplash/vigsqYux_-8.jpg" alt="Example image" />
      </div>
    </div>