Controlling the size of an image within a CSS Grid layout

martin picture martin · Sep 7, 2017 · Viewed 69.6k times · Source

I have a CSS grid layout with a bunch of areas and a photo container.

I don't know how to:

  1. control the size of the photo, so that it is contained within the area of the grid

  2. keep the width of the photo at 100% (thus equal to its container) and scale the height of the container to fit the photo. Basically, when the window becomes smaller, the width of the photo becomes smaller, and so does the height - pulling the tag, album, and rotate elements up.

Answer

Michael Benjamin picture Michael Benjamin · Sep 7, 2017

You have two different problems here.

I'll address the first one, which is to contain the image in its container. You almost had it.

Your code:

.photo > img {
  object-fit: cover;
  width: 100%;
}

You just needed to specify a maximum height on the image so it could not overflow the container:

.photo > img {
  object-fit: cover;
  width: 100%;
  max-height: 100%;
}

JSFiddle demo


The second problem, which is to scale the size of the image container, and drag up the grid items below when the image gets smaller, is significantly more complex.

This isn't an issue relating to the image. In fact, you can remove the image altogether when trying to solve this problem.

This is an issue of dynamically sizing a grid item (the image container). Why would this grid item change size in relation to the image size, when its size is being controlled by grid-template-columns and grid-template-rows?

In addition, why would the bottom row of grid items (tag, album, rotate) follow the image container either up or down? They would have to exit their row.

Scaling the entire grid container wouldn't be a problem. But it seems like you only want to scale one grid item (the image container). It's tricky. You're probably looking at additional containers, auto values for lengths, and possibly scripting.

Here's what happens if you give the image rows an auto value: JSFiddle demo