Object-fit: contain for a div element

42 Views Asked by At

As I know, the <img/> have css prop: object-fit.

When value is contain: img will be display full, and there is white space (if the ratio of image is different from <img/>).

Now. I have a div, has a ratio 3/2. The parent is an div with height and width is dynamic, and no ratio for parent.

How can the children always inside the parent (contain) in any ratio of parent?

1

There are 1 best solutions below

0
imhvost On

You can set img { max-width: 100%; max-height: 100%; }:

img {
  max-width: 100%;
  max-height: 100%;
}

div {
  outline: solid 1px blue;
  margin: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

div:nth-child(1) {
  width: 100px;
  height: 100px;
}

div:nth-child(2) {
  width: 160px;
  height: 60px;
}

div:nth-child(3) {
  width: 60px;
  height: 80px;
}
<div><img src="https://picsum.photos/300/200" alt=""></div>
<div><img src="https://picsum.photos/300/200" alt=""></div>
<div><img src="https://picsum.photos/300/200" alt=""></div>