如何使用响应大小的图像来防止混乱和减少布局偏移? [英] How can I prevent jank and reduce layout shift with responsive sized images?

查看:23
本文介绍了如何使用响应大小的图像来防止混乱和减少布局偏移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上托管了许多各种尺寸的图像.这些图像具有响应性,并且可以在所有浏览器宽度(从台式机到移动设备)上更改尺寸.我在Google Search Console中看到我的.25s的CLS(累积布局偏移)很差.我的网站布局随着图片的加载而变化.

My website hosts a lot of images of all sizes. These images are responsive and change size at all browser widths from desktop to mobile. I see in my Google Search Console that I have a poor CLS (cumulative layout shift) of .25s. The layout of my website shifts as the images load.

由于我的图像具有响应能力,因此我无法指定图像的确切大小,也无法使用占位符来保留空间.

Since my images are responsive, I can't specify exact sizes of the images, or have placeholders to reserve the space.

用响应图像来防止CLS的现代方法是什么?

What is a modern way to prevent CLS with responsive images?

此处的布局: https://jsfiddle.net/exspwgab/

更新:我在互联网上尝试了一项建议,即在img标签中指定图像文件的宽度和高度,例如:

Update: I tried one suggestion on the internet which is to specify the image file's width and height within the img tag like:

<img src="photo.jpg" width="1504" height="752">

然后在CSS中执行:

width: 100%;
height: auto;

这似乎不适用于任何浏览器.加载图像后,网页上的元素仍然四处移动.

This didn't seem to work in any browser. And the elements on my webpage still moved all over as the images loaded.

如果任何人都有适用于所有浏览器的解决方案,请告诉我.我基本上需要占位符来容纳图像加载时的空间,以防止页面出现问题.

If anyone has a solution that works in all browsers please let me know. I essentially need placeholders to hold the space while the images load to prevent the page jank issue.

JSF我的响应式布局的中间在这里: https://jsfiddle.net/exspwgab/

JSFiddle of my responsive layout here: https://jsfiddle.net/exspwgab/

推荐答案

我最终使用了在这里找到的解决方案:

I ended up using the solution found here: http://davidecalignano.it/lazy-loading-with-responsive-images-and-unknown-height/#:~:text=And%20here%20is%20the%20formula,flashes%20on%20lazy%20loaded%20images.

HTML

<a class="thumb lazy-container" href="#">
 <img class="lazy" data-original="image.jpg" alt="">
</a>

CSS

.lazy-container {
 display: block;
 position: relative;
 height: 0;
}

.post .lazy-container {
 padding-bottom: 55.3%;
}

.lazy-container img {
 position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 height: 100%;
}

由于所有图像的高度都不同,因此我将填充底部的百分比作为每个图像的内联样式.

Since all of my images have a different height, I put the padding-bottom percentage as an inline style for each image.

这篇关于如何使用响应大小的图像来防止混乱和减少布局偏移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆