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

I want to include an image that should scale up to either a max-width or a max-height without changing the aspect ratio of that image. This should work for any possible image size.

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

旁注:一个人可以用一些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 */
  width: 100%;
  height: auto;
}

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

As said before, it works for large images (they automatically "try to be" as large as their pixel size): large image

But it does not work for small images: small image

评论