1

I have a grid with 3 rows each with a particular proportion. I want these rows to always take the full current viewport height - no more, no less. So I tried the following:

.grid {
  display: grid;
  grid-template-rows: 3fr 2fr 4fr;
  height: 100vh;
}

<div class="grid">
  <div>Row 1</div>
  <div>Row 2</div>
  <div>Row 3</div>
</div>

This works fine as is. But then say if I try and add a large image to the first row:

img {
  object-fit: contain;
  width: 100%;
  height: 100%;
  max-height: 100%;
}

<div class="grid">
  <div>
    <img src="https://images.unsplash.com/photo-1482003297000-b7663a1673f1?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ"/>
  </div>
  <div>Row 2</div>
  <div>Row 3</div>
</div>

Now the first row is expanded to accommodate the full image. How can I force the image to be shrunk such that the first row's proportion is maintained as before?

Full example saved here on Codepen

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
user79074
  • 4,937
  • 5
  • 29
  • 57
  • Grid items cannot, by default, be smaller than their content. You need to override that default. https://jsfiddle.net/jgc5pqe3/ – Michael Benjamin Apr 02 '20 at 16:56
  • Here's the same demo in codepen: https://codepen.io/Figueroa5566/pen/GRJLLEE – Michael Benjamin Apr 02 '20 at 19:52
  • Unfortunately this solution stops working if I place this grid within another grid which is the solution I am looking for. I have updated the the Codepen demo accordingly: https://codepen.io/hughgearse/pen/Poqgyyv – user79074 Apr 02 '20 at 20:10
  • You need to set a height on the nested grid. https://codepen.io/Figueroa5566/pen/MWwRMqV – Michael Benjamin Apr 02 '20 at 21:46

0 Answers0