保持宽高比将任何图像缩放到最大宽度/最小宽度

时间:2020-05-23 13:09:57

标签: html css

我想包含一个图像,该图像应按比例缩放到max-widthmax-height,而无需更改该图像的纵横比。这应该适用于任何可能的图像尺寸。

但是我想出的版本不适用于小图像(也应该放大)。

侧面说明:我可以使用一些javascript做到这一点,但是有什么方法可以使用普通的CSS做到这一点?

<body>
  <div class="ImageContainer">
    <!-- Works for large images -->
    <!--<img src="/assets/American-Magic-1200x628.jpg"/>-->

    <!-- Does not work for small images -->
    <img src="/assets/American-Magic-250x131.jpg" />
  </div>
</body>
* {
  padding: 0;
  margin: 0;
}

body {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgb(125, 125, 125);
}

.ImageContainer {
  /*
  width: calc(100vw - 32px);
  height: calc(100vh - 32px);

  max-width: calc(100vw - 32px);
  max-height: calc(100vh - 32px);
  */

  border-radius: 4px;
  overflow: hidden;

  background-color: rgb(
    220,
    100,
    100
  ); /* just visualizing the not-wanted region */
}

.ImageContainer img {
  display: block; /* No whitespace below image */
  max-width: calc(100vw - 32px);
  max-height: calc(100vh - 32px);
}

Edit max-image-fit-for-small-images

如前所述,它适用于大图像(它们会自动“尝试”成为其像素大小): large image

但不适用于小图像: small image

1 个答案:

答案 0 :(得分:1)

您可以将imageContainer div设置为全角和全角,然后在图像上使用object-fit:contains。这将使图像填充包含元素,同时保持宽高比。

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

Codesandbox...

.ImageContainer {
  width: calc(100vw - 32px);
  height: calc(100vh - 32px);

  /*
  max-width: calc(100vw - 32px);
  max-height: calc(100vh - 32px);
  */

  border-radius: 4px;
  overflow: hidden;

  background-color: rgb(
    220,
    100,
    100
  ); /* just visualizing the not-wanted region */
}

.ImageContainer img {
  /* display: block; No whitespace below image */
  /* max-width: calc(100vw - 32px);
  max-height: calc(100vh - 32px); */

  height: 100%;
  width: 100%;
  object-fit: contain;
}