我正在处理一个响应式网页,其中的图像可能大于移动浏览器屏幕的 max-width
。在下面的示例中,我使用了来自 https://stackoverflow.com/company 的图像这是 975x573。
考虑这个片段。
img {
max-width: 100%;
height: auto;
}
<img height="573" width="975" src="https://cdn.sstatic.net/Sites/stackoverflow/company/Img/photos/big/1.jpg?v=17b956bfb68e">
<p>test</p>
<img height="573" width="975" src="https://stackoverflow.com/missing-image.png">
<p>test</p>
此示例包含两张图片,一张存在,一张不存在。
我希望两个图像的图像框高度相同,宽度为 100%,并保留纵横比。
相反,现有图像会在保留其宽高比的情况下正确调整大小,但损坏的图像为 16x16,这(在我的完整站点中)使我的布局看起来很奇怪。
我该如何修正这个例子? (请仅使用纯 CSS。)
最佳答案
似乎无法按照我想要的方式设置损坏图像的样式。我能找到的唯一解决方法是使用包装 div,force the div to maintain a fixed aspect ratio ,并强制图像填充其包装父级。
在上面的链接中有很多技术可以做到这一点。例如,这是一个。
.wrapper {
max-width: 100%;
padding-bottom: 58.77%; /* 573/975 */
position: relative;
}
img {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
max-width: 100%;
max-height: 100%;
}
<div class="wrapper"><img src="https://cdn.sstatic.net/Sites/stackoverflow/company/Img/photos/big/1.jpg?v=17b956bfb68e"></div>
<p>test</p>
<div class="wrapper"><img src="https://stackoverflow.com/missing-image.png"></div>
<p>test</p>
关于html - 强制损坏图像以保留硬编码的纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50403308/