设置图像的宽度/高度以避免图像加载时重新流动

gab*_*bor 23 html image css3 responsive-design

当我在html中使用图像标签时,我尝试在标签中指定其宽度和高度img,以便浏览器甚至在加载图像之前为它们保留空间,因此当它们完成加载时,页面不会重排(元素不会四处移动).例如:

<img width="600" height="400" src="..."/>
Run Code Online (Sandbox Code Playgroud)

问题是现在我想创建一个更"响应"的版本,对于"单列案例",我想这样做:

<img style="max-width: 100%" src="..."/>
Run Code Online (Sandbox Code Playgroud)

但是,如果我将其与明确指定的宽度和高度混合使用,例如:

<img style="max-width: 100%" width="600" height="400" src="..."/>
Run Code Online (Sandbox Code Playgroud)

并且图像比可用空间宽,然后忽略宽高比调整图像大小.我明白为什么会发生这种情况(因为我"修复了"图像的高度),我想解决这个问题,但我不知道怎么做.

总结一下:我希望能够指定max-width: 100%,并且还能以某种方式确保在加载图像时内容不会被重排.

wii*_*lll 10

更新 2:(2019 年 12 月)

Firefox 和 Chrome 现在默认处理这个问题。只需像往常一样添加widthheight属性。有关更多详细信息,请参阅此博客文章


更新 1:(2018 年 7 月)

我发现了一个更聪明的替代版本:http : //cssmojo.com/aspect-ratio-using-custom-properties-and-calc/。这仍然需要一个包装元素,它需要 CSS 自定义属性,但我认为它更优雅。Codepen 示例在这里(归功于 Chris Coyier 的原创)。


原来的:

来自Jonathan Hollin 的这篇博客文章:将图像的高度和宽度添加为内联样式的一部分。这为图像保留了空间,防止图像加载时回流,但它也是响应式的。

HTML

<figure style="padding-bottom: calc((400/600)*100%)">
  <img src="/images/kitten.jpg" />
</figure>
Run Code Online (Sandbox Code Playgroud)

CSS

figure {
  position: relative;
}

img {
  max-width: 100%;
  position: absolute;
}
Run Code Online (Sandbox Code Playgroud)

figure可以用更换div或您选择的任何其他容器。该解决方案依赖于具有广泛浏览器支持的CSS calc() 。

工作 Codepen 可以在这里看到。

  • 抱歉,当您说“这和以前一样”时,您指的是什么?我觉得我的答案不是任何其他答案的重复,它回答了这个问题。有什么办法可以改进吗? (2认同)

小智 8

我也在寻找这个问题的答案.有了max-width,width=并且height=,浏览器有足够的数据,它应该能够为图像留出适当的空间,但它似乎不会那样工作.

我现在用jQuery解决方案解决了这个问题.它要求你提供width=height=你的<img>标签.

CSS:

img { max-width: 100%; height: auto; }
Run Code Online (Sandbox Code Playgroud)

HTML:

<img src="image.png" width="400" height="300" />
Run Code Online (Sandbox Code Playgroud)

jQuery的:

$('img').each(function() { 
    var aspect_ratio = $(this).attr('height') / $(this).attr('width') * 100;
    $(this).wrap('<div style="padding-bottom: ' + aspect_ratio + '%">');
});
Run Code Online (Sandbox Code Playgroud)

这会自动应用以下技术:http://andmag.se/2012/10/responsive-images-how-to-prevent-reflow/