我有 1000 像素宽 x 250 像素高的图片。我通过使用
使图像具有响应性/灵 activeimg {
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/