0

How do I resize/scale a centered image to fill its parent when the parent container dimensions are unknown?

No cropping or stretching, just resize or scale until image fills its parent width or height.

See the below layouts (codepen for reference):

enter image description here

The child image fits its parent container as expected when at least one dimension of the child exceeds one dimension of the parent, but I cannot get the image to stretch and fill the parent when the image is smaller in both dimensions than its container (see 150x150 and 150x50 cases).

Hod do I achieve image filling its parent for all cases using CSS only?

My css for reference (see link to codepen above):

.parent {
  position: relative;
  background: gray;

  display: inline-block;
}
.square {
  width: 200px;
  height: 200px;
}
.tall {
  width: 200px;
  height: 300px;
}
.wide {
  width: 300px;
  height: 200px;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 0;
  right: 0;
  margin: auto;
  max-width: 100%;
  max-height: 100%;
}
Miki
  • 1,625
  • 21
  • 29

0 Answers0