0

I have a nice little table with 4 elements which contain images.

The images are usually uploaded by users, so I don't have exact control over the image size.

What I am trying to do is create a 2 x 2 layout which resizes to fit the users screen and each box in the layout is given a 16:9 aspect ratio.

This works really well adjusting the window width, but if the user adjusts the height, the elements overflow rather than adjusting in height to fit the users screen.

You can see example here, and if you adjust your screen the horizontal width behavior is what I'm looking for, but adjusting vertically hides the images on smaller window sizes. https://codepen.io/anon/pen/zaXEOL

.outer-grid {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  max-height: 70vh;
  max-width: 70vw;
  overflow: hidden;
}

.holder {
  border: 1px solid red;
  max-width: 46%;
  max-height: 46%;
  margin: 1%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 0;
  padding-top: 26%;
  width: 100%;
  position: relative;
}

img {
  object-fit: contain;
  max-height: 100%;
  top: 0;
  max-width: 100%;
  width: 100%;
  height: 100%
<div class="outer-grid">
  <div class="holder">
    <img src="http://fillmurray.com/200/300"/>
  </div>
   <div class="holder">
    <img src="http://fillmurray.com/300/300"/>
  </div>
     <div class="holder">
    <img src="http://fillmurray.com/300/200"/>
  </div>
     <div class="holder">
    <img src="http://fillmurray.com/250/300"/>
  </div>
</div>

The css I am using is fairly simple

.outer-grid {
  display: grid;
  grid-template-columns: repeat(2,1fr);
  grid-template-rows: repeat(2,1fr);
  grid-gap: 1rem;
  max-height: 70vh;
  max-width: 70vw;
  overflow: hidden;
}

.holder {
  border: 1px solid red;
  max-width: 100%;
  max-height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 0;
  padding-top: 56%;
  position: relative;
}

img {
  position: absolute;
  display: block;
  top: 0;
  max-height: 100%;
  max-width: 100%;
}
pedalpete
  • 21,076
  • 45
  • 128
  • 239

1 Answers1

2

First, note that your layout doesn't work at all in Firefox and Edge. This is because the percentage padding trick you are using, when applied in a grid container, doesn't work in all browsers. Here is a detailed explanation: Percentage padding / margin on grid item ignored in Firefox

Second, percentage padding re-sizes images based on their width. That's the whole trick.

From the spec:

ยง 8.4 Padding properties: padding-top, padding-right, padding-bottom, padding-left, and padding

<percentage>

The percentage is calculated with respect to the width of the generated box's containing block, even for padding-top and padding-bottom.

The images can re-size on the horizontal axis because percentage padding is associated with width. They can't re-size on the vertical axis because percentage padding has no association with height.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701