强制破碎图像以保留硬编码宽高比

时间:2018-05-18 03:22:07

标签: html css

我正在处理一个响应式网页,其中的图片可能比移动浏览器屏幕的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。)

2 个答案:

答案 0 :(得分:0)

似乎不可能按照我想要的方式设置损坏的图像。我能找到的唯一解决方法是使用包装器div force the div to maintain a fixed aspect ratio,并强制图像填充其包装父级。

在上面的链接中有很多技术可以做到这一点。例如,这是一个。

list_1 = [100, 100, 50, 40, 40, 20, 10]
list_2 = [5, 25, 50, 120]

final_list = []

for l1 in list_2:
    temp_list_1 = list_1.copy()
    temp_list_1.append(l1)        
    temp_list_1.sort(reverse=True)

    final_list.append(temp_list_1)

print(final_list)
.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%;
}

答案 1 :(得分:0)

让我说清楚,“破碎的图像”只是浏览器渲染图像,以显示它已损坏,您无法访问该“图标”。因此,在某些浏览器中,由于某些浏览器不支持,因此无法显示。

获得与预期相同结果的最佳解决方案是使用背景图像作为图像元素。请查看下面的代码片段:

你必须定义宽高比,在我的代码中,我已经在heightwidth =&gt;之间的分区定义了宽高比。 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>