【问题标题】:Set height of image with 100% width for CLS (Cumulative Layout Shift)为 CLS(累积布局移位)设置 100% 宽度的图像高度
【发布时间】:2020-12-20 03:12:08
【问题描述】:

为了处理 Core Web Vitals 的 CLS,我需要找到一种方法来在屏幕上的图像为 100% 宽度时设置 img 标记的高度,因为 图像的高度会随着窗口的变化而变化调整大小。我正在开发的网站是基于 WordPress 构建的,并找到了解决方法。所以,我会写下如何在 WordPress 上管理它。

【问题讨论】:

    标签: html css image web-vitals


    【解决方案1】:

    图像的最佳实践

    执行 OP 要求的更通用方法是使用原生 widthheight 属性在图像上简单地设置宽度和高度(以像素为单位)。

    This is what is advised as the modern best practice

    假设浏览器拥有计算宽度所需的所有信息(来自内联 CSS),现代浏览器将为图像分配足够的空间以避免布局偏移。

    这些宽度和高度不必是图像将显示的实际尺寸,只要是正确的比例即可。

    所以在下面的示例中,我们获取图像缩略图的宽度和高度(比如 640 像素宽和 480 像素高)。

    然后我们在 CSS 中设置图像相对于其容器的宽度(在本例中为页面宽度的 50%)。

    然后浏览器将为图像分配正确的高度以避免布局偏移。 (在下面的示例中,假设屏幕宽度为 1920 像素,它将分配 720 像素的高度 - 由于 50% 的宽度,一个 960 像素宽的图像,然后是 720 像素的高度以保持纵横比。)

    $img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) , 'thumbnail' );
    $src = $img[0]; 
    $height = $img[1]; //e.g. 640(px)
    $width = $img[2]; //e.g. 480(px)
    
    
    
    <style>
        img{
           width: 50%; 
           height: auto; /*this is important as otherwise the height set on the image will be used*/
        }
    </style>
    
     <img src="<?php echo $src; ?>" width="<?php echo $width; ?>" height="<?php echo $height; ?>" />
    

    小提琴演示

    在下面的小提琴中,我加载了一个大图像(您可能仍想添加节流以查看没有布局偏移)。空间由浏览器自动计算,因此不会发生布局偏移。

    最大的优势是以下内容适用于媒体查询(因为您可以在内联 CSS 中设置任何宽度)并且可以与内容安全策略一起正常工作,因为它不依赖内联 style 项目。

    <style>
       img{
          width: 50%;
          height: auto;
       }
    </style>
    
    
    <img src="http://picserio.com/data/out/369/sahara-desert-wallpaper_5757536.jpg" width="6400" height="4800" />
    <p>I don't shift</p>

    【讨论】:

    • 感谢您的评论!所以,当我们设置一个特定的宽度,甚至像width 100%,设置height: auto 应该照顾它,意味着不会发生布局偏移?
    • 只要您还向图像添加宽度和高度作为正确比例的内联属性,就可以!
    • 这个很方便。
    【解决方案2】:

    首先,我们可以通过wp_get_attachment_image_src获取图片的宽高。

    $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) , 'thumbnail' );
    
    // $featured_image[0]: URL of an image
    // $featured_image[1]: Width of an image
    // $featured_image[2]: Height of an image
    

    通过CSS的100vw$featured_image的值,我们可以得到图片的高度。

    $ratio = $featured_image[2] / $featured_image[1];
    

    然后,将其设置为如下高度。

    <img 
        src="<?php echo $featured_image[0]; ?>"
        style="
            width: 100%;
            height: calc(100vw * <?php echo $ratio ;?>);
        "
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-23
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      相关资源
      最近更新 更多