Search code examples
htmlcsscss-grid

CSS Grid: Picture overflow in height


I have a simple CSS grid with 2 columns (60%, 40%). The first one is filled with a picture. The picture is well contained inside the grid when it has enough height.

The problem is when it has not enough height, the picture is overflowing in height.
I would like it to stay inside the grid and fill it whatever the window size.

Here's the code:

.container {
  display: grid;
  grid-template-columns: 60% 40%;
  height: 100vh;
  border: 2px solid red;
}

.picture {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="container">
  <img class="picture" src="https://i.pinimg.com/550x/e4/7e/00/e47e006f1cf838ccf5468e8548a7577c.jpg">
  <p class="text">Some text</p>
</div>

Here's a JSFiddle: https://jsfiddle.net/f4us5krq/1/


Solution

  • You can set your height on your container to be 100% and that way the picture will fit inside. You can try overflow: hidden; on the .picture if you still want to use height: 100vh;

    .container {
      display: grid;
      grid-template-columns: 60% 40%;
      height: 100vh;
      border: 2px solid red;
    }
    
    .picture {
      width: 100%;
      height: 100%;
      object-fit: cover;
      overflow: hidden;
    }
    <div class="container">
      <img class="picture" src="https://i.pinimg.com/550x/e4/7e/00/e47e006f1cf838ccf5468e8548a7577c.jpg">
      <p class="text">Some text</p>
    </div>