在浏览器布局中为响应式图像保留空间(防止回流)

2022-01-19 00:00:00 image browser frontend javascript css

我一直在进行更改,以使我的网站更具响应性,总的来说,这进展顺利.但是,我遇到了一个问题:

I have been making changes to make my site more responsive and, in general, this has gone well. However, I have run into one problem:

以前,我总是在 img 元素上使用 height 和 width 属性,以便在浏览器加载图像时在布局中保留空间.这可以防止布局在浏览器中晃动加载并计算图像所需的空间.

Before, I always used height and width attributes on img elements in order to reserve space in the layout for the images while the browser loads them in. This prevents the layout from jerking around while the browser loads and calculates the needed space for the image.

然而,在使我的图像更具响应性之后,通过使用 max-width: 100% 并取出 height 和 width 属性,浏览器不再为图像保留空间(因为它不再提前知道图像的高度或宽度,因为我无法明确告诉它)

After making my images more responsive, however, by using max-width: 100% and taking out the height and width attributes, the browser no longer reserves space for the image (because it no longer knows how tall or wide the image is going to be in advance since I couldn't explicitly tell it)

我的目标是让响应式图像在初始加载时也占据页面布局中的适当空间.有谁知道这个的解决方案吗?

My goal is to have responsive images that also take up their appropriate space in the page layout upon its initial load. Does anyone know of a solution for this?

*编辑(解决方案) - 这是我找到的关于该主题的最佳文章.不错的方法!

推荐答案

这里的正确答案是使用padding-bottom技巧"来防止垂直回流.要使这项技术发挥作用,您必须事先知道图像的比例.

The correct answer here is to prevent the vertical reflow by using the "padding-bottom trick". To make this technique work, you must know the proportions of the image in advance.

感谢 Anders M. Anderson 就该主题发表了一篇出色的文章:http://andmag.se/2012/10/responsive-images-how-to-prevent-reflow/

Thanks to Anders M. Anderson for posting an excellent article on the topic: http://andmag.se/2012/10/responsive-images-how-to-prevent-reflow/

相关文章