css - 对象适合响应图像

标签 css

我有 1000 像素宽 x 250 像素高的图片。我通过使用

使图像具有响应性/灵 active
img { 
max-width:1000px; 
height:auto; 
}

所有图片的比例应为 1 到 1/4。

不过,从现在开始,客户端将使用 CMS 来替换和更新图像。我无法控制这些新图像的尺寸。 CMS 无法将新图像缩放和裁剪为所需格式。我被告知使用 object:fit。如:

img { 
width:1000px;
height:250px;
object-fit:cover;
}

然而,这些意味着图像不具有响应性/灵 active 。有没有办法让图像保持响应并使比例保持不变?

我尝试了以下方法,但它们不起作用:

img {
max-width: 100%;
max-height: 252px;
object-fit: cover;
}

img {
max-width: 100%;
height: auto;
object-fit: cover;
}

我可以使用背景图片和 padding-bottom:25% 技巧,但我更愿意使用图片和 alt 标签。

最佳答案

2022 年更新

现在你可以依赖aspect-ratio

img.responsive {
  width: 100%;
  aspect-ratio:4;
  object-fit: cover;
}
<img src="https://picsum.photos/id/1000/1000/1000" alt="image" class="responsive">
<img src="https://picsum.photos/id/1074/1000/1000" alt="image" class="responsive">


旧答案

您可以结合使用 img 和填充技巧。您只需要为与 src 相同的背景图像添加一个额外的内联样式:

img {
  width: 100%;
  height: 0;
  padding-top: 25%;
  background-size: cover;
  background-position: center;
}
<img src="https://picsum.photos/id/1000/1000/1000" style="background-image:url(https://picsum.photos/id/1000/1000/1000g)" alt="image">

用一个小的 JS 代码你可以自动得到这个:

$('.responsive').each(function() {
  $(this).css('background-image','url('+$(this).attr('src')+')');
})
img.responsive {
  width:100%;
  height:0;
  padding-top:25%;
  background-size:cover;
  background-position:center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://picsum.photos/id/1000/1000/1000"  alt="image" class="responsive">
<img src="https://picsum.photos/id/1074/1000/1000"  alt="image" class="responsive">

关于css - 对象适合响应图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61681351/

相关文章:

html - css 背景颜色的无效属性值

javascript - 如何在没有滚动条的情况下显示比浏览器窗口大的图像并保留整个图像?

jquery - 在滚动上显示 html5/youtube 视频

javascript - 如何对动态生成的表行设置限制?

css - 如何通过CSS在 anchor 标签后放置背景?

html - 网页中的动态背景调整大小

css - 斜边按钮

css - 如何检测缺少位置 :fixed in a generic way?

css 表阴影外面不显示

html - 制作一个文本区域,其中每个字符的宽度始终相同