[英]Force broken image to preserve hard-coded aspect ratio
我正在使用包含比移动浏览器屏幕的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, 强制div保持固定的宽高比 ,并强制图像填充其包装器父级。
上面的链接中有很多技术可以做到这一点。 例如,这是一个。
.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>
让我清楚一点,“损坏的图像”只是浏览器呈现的图像,向您显示它已损坏,您无法访问该“图标”。 因此,在某些浏览器中,由于某些浏览器不支持,因此无法显示。
获得预期效果相同的最佳解决方案是将背景图像用作图像元素。 请检查以下代码段:
您必须定义纵横比,在我的代码中,我已经通过在height
和width
=> 573/975
之间进行划分来定义了纵横比。
更多信息: https : //www.w3schools.com/howto/howto_css_aspect_ratio.asp
img { width: 100%; height: auto; } .img-cover { background-image: url(http://via.placeholder.com/975x573); background-repeat: no-repeat; background-size: cover; width: 100%; padding-top: 58.769%; /* Aspect Ratio from 573/975 */ position: relative; /* If you want text inside of it */ } .inner { position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
<div class="img-cover"> <div class="inner"> <img height="573" width="975" src="https://cdn.sstatic.net/Sites/stackoverflow/company/Img/photos/big/1.jpg?v=17b956bfb68e"> </div> </div> <p>test</p> <div class="img-cover"> <div class="inner"> <img height="573" width="975" src="https://stackoverflow.com/missing-image.png"> </div> </div> <p>test</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.