html - 如何使图像适合其 div CSS

标签 html css image web-frontend

假设我有以下代码:

img {
  max-widht: 100%;
  max-height: 100%;
}
<div width="500" height="500">
  <img src="https://placehold.it/250x150">
</div>

如果 widthheight 大于 500px,这对所有图像都有效。 但是对于较小的图像,图像将不会覆盖 div。 有没有一种 CSS 方法可以强制图像至少为 width: 100%height: 100% 而不管其原始大小?

编辑: 此解决方案由 disinfor为我工作。

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

最佳答案

这样做:

img {
    width: 100%;
    height: auto;
}

较小的图像(在您的例子中,宽度小于 500 像素)没有填满整个空间的原因是因为 max-width 表示“实际图像的最大宽度”。因此,如果您改用 width: 100%,图像将填满其容器的空间。

使用 height: auto 将确保图像不会被垂直拉伸(stretch)/扭曲。

概念验证:

.normal, .land, .port, .fit {
  height: 200px;
  width: 200px;
}

img {
  width: 100%;
  height: auto;
}

div.land img,
div.port img {
  width: 100%;
  height: 100%;
}

div.fit img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="fit">
  <img src="https://placehold.it/500x750">
</div>

<div class="fit">
  <img src="https://placehold.it/50x100">
</div>

<div class="normal">
  <img src="https://placehold.it/75x10">
</div>

<div class="normal">
  <img src="https://placehold.it/10x75">
</div>

<div class="land">
  <img src="https://placehold.it/75x10">
</div>

<div class="port">
  <img src="https://placehold.it/10x75">
</div>

关于html - 如何使图像适合其 div CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54934081/

相关文章:

html - <div> 旁边的 <img> 的 CSS,带有文本和最小宽度

html - 打开我的网站时无法加载 css 文件

JavaScript 图像作为按钮 (onClick)

javascript - 生成 Angular JS href

html - 自己的菜单栏 - 一行中只有一个

html - 如何使按钮宽度在媒体查询中起作用

jquery - Twitter Bootstrap 更改导航栏

css - 移动 View 中的 html5 有边框,但在 pc View 中没有

css - 如何在将鼠标悬停在图像上时在标签中显示图像名称

delphi - JPEG-LS/LOCO-I 压缩库