html - 强制损坏图像以保留硬编码的纵横比

标签 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。)

最佳答案

似乎无法按照我想要的方式设置损坏图像的样式。我能找到的唯一解决方法是使用包装 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/

相关文章:

html - 网页主区 : div height issue

javascript - Jquery Chat 使用 angularjs 绑定(bind)作为用户名

javascript - 如何添加淡入淡出效果

javascript - 如何使用图像映射写入区域的文本中心?

css - Knockout 数据绑定(bind)通过背景颜色对比更改文本颜色

javascript - 如何通过 Javascript 加速 HTML 操作,和/或提高动画的渲染速度?

javascript - 将今天的日期放在多个文本框中单击

html - 如何防止 Bootstrap 按钮从其他类继承?

javascript - 传单 map 不显示

javascript - 带有框阴影的 Safari 溢出滚动 - 仍然能够处理溢出的元素