1

I'm trying to make an image gallery, and I want images to take half the height and half the width available in the container, so I did something like this:

* {
  padding: 0;
  margin: 0;
}

div {
  height: 200px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
}

div > figure > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div>
  <figure>
    <img src="http://lorempicsum.com/futurama/327/100/1">
  </figure>
  <figure>
    <img src="http://lorempicsum.com/futurama/427/200/2">
  </figure>
  <figure>
    <img src="http://lorempicsum.com/futurama/527/300/3">
  </figure>
  <figure>
    <img src="http://lorempicsum.com/futurama/627/200/4">
  </figure>
</div>

Now what I don't understand is why my images aren't 100px high? Isn't the fr unit supposed to distribute space evenly between my figures? Why doesn't it behaves the same way as it would if I did grid-template-rows: repeat(2, 100px); or grid-template-rows: repeat(2, 50%);?

Edit

I just stumbled upon this post where it says

The fr unit fills up the available space BUT it is NEVER smaller than the content of the row or column

But does that mean I just can't use fr units in this case?

evuez
  • 3,257
  • 4
  • 29
  • 44
  • 2
    An initial setting on grid items is `min-height: auto`. This means that a grid item cannot be smaller than the size of its content. The heights of your images (100px, 200px, 300px) force the grid items, when stacked, to exceed the height of the container (200px). Override the `min-height` default. Add `min-height: 0` to your grid items (`figure`). https://jsfiddle.net/yL74vx2s/ – Michael Benjamin Oct 20 '17 at 13:40

1 Answers1

-1

I think you need width in div

* {
  padding: 0;
  margin: 0;
}

div {
  height: 200px;
width:200px;

  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
}

div > figure > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div>
  <figure>
    <img src="http://lorempicsum.com/futurama/327/100/1">
  </figure>
  <figure>
    <img src="http://lorempicsum.com/futurama/427/200/2">
  </figure>
  <figure>
    <img src="http://lorempicsum.com/futurama/527/300/3">
  </figure>
  <figure>
    <img src="http://lorempicsum.com/futurama/627/200/4">
  </figure>
</div>
Raspberryano
  • 159
  • 1
  • 10