html - CSS纵横比覆盖图像断点?
问题描述
我一直试图找出页面速度见解和我网站上的特色图片的问题。
有问题的页面是https://streamershaven.blog/twitch/twitch-panels/
我最近在我的网站中添加了宽高比顶部填充技巧,以使图像保留所需的空间,以避免出现 CLS 标志。虽然这有效,但它引入了一个新问题 - 现在不再尊重设备宽度断点,您可以在此处看到:
<img width="960" height="480" src="https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained-960x480.jpg" data-src="https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained-960x480.jpg" class="attachment-960x480x1 size-960x480x1 lazyloaded" alt="Twitch Panels Explained" itemprop="image" data-srcset="https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained-960x480.jpg 960w, https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained-300x150.jpg 300w, https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained-768x384.jpg 768w, https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained-150x75.jpg 150w, https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained.jpg 1280w" sizes="(max-width: 960px) 100vw, 960px" title="Twitch Panels - an Essential Asset for all Twitch Streamers 1" srcset="https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained-960x480.jpg 960w, https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained-300x150.jpg 300w, https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained-768x384.jpg 768w, https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained-150x75.jpg 150w, https://streamershaven.blog/wp-content/uploads/2021/04/twitch-panels-explained.jpg 1280w">
用于实现纵横比填充技巧的 css 代码:
.single .featured-image img {
position: absolute;
top: 0;
left: 0;
max-width: 100%;
height: auto;
}
.single .featured-image {
position: relative;
height: 0;
padding-top: calc(480 / 960 * 100%);
}
使用这种方法的结果基本上已经迫使浏览器对所有断点使用 960w 图像变体,导致为较小的屏幕尺寸下载不必要的 kb。
删除 CSS 解决了这个问题 - 但以 CLS 命中为代价。我尝试过最小高度,但这并不理想,因为当图像按比例缩小时,这会导致媒体断点之间的空白空间更大。
有没有更好的方法来完成这项符合 CLS 的任务并确保它交换到适当的图像尺寸?
解决方案
试试这个CSS:
.single .featured-image {
max-width: 960px;
width: 100%;
position: relative;
height: 0;
overflow: hidden;
padding-top: 50%; /*480*100/960*/
}
.single .featured-image img {
position: absolute;
width: 100%;
height: 100%;
left: 50%;
top: 50%;
object-fit: cover;
transform: translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
}
注意:从 img 标签中删除宽度和高度https://prnt.sc/12awa8h
推荐阅读
- swift - 如何从 NSDocument 的 read 方法中获取数据
- javascript - 如何从 javacsript 中的现有 JSON 对象中获取特定的键值?
- jvm - 无法从堆分配内存
- bash - 终端打开时出错:-bash: /nvm.sh: No such file or directory
- deployment - 在谷歌云的部署管理器中使用 gcp-types/servicenetworking.googleapis.com:services.connections
- java - OpenGL glBufferSubData - 无法让它工作
- php - 如何仅通过用户 ID 获取报告?
- excel - VBA中的超链接循环和if语句包含模式
- postgresql - 按值查找 jsonb 文档数组中的元素,不区分大小写
- python - 我们如何使用 BigQueryCreateEmptyTableOperator 创建具有“Clustered by”列的表?