1

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/

PepeW
  • 477
  • 1
  • 8
  • 24

2 Answers2

1

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>
Kameron
  • 10,240
  • 4
  • 13
  • 26
0

Change width and height to inherit. Add max width/height to stop overflow if the grid is too tight.

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

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

P.S you can also experiment with object-fit: contain

Dominic
  • 62,658
  • 20
  • 139
  • 163