简体   繁体   English

灯塔:设置显式宽度和高度的问题

[英]Lighthouse: Problem setting explicit width and height

I'm currently trying to improve the Lighthouse score for my website.我目前正在尝试提高我网站的 Lighthouse 分数。 The biggest problem that Lighthouse shows is that I don't use an explicit width and height for my images. Lighthouse 显示的最大问题是我没有为我的图像使用明确的宽度和高度。 The problem with this is that my images pretty much all have very different aspect ratios and with new images being added all the time there is no way to fix this manually.问题在于我的图像几乎都有非常不同的纵横比,并且一直在添加新图像,因此无法手动修复此问题。 What options are there to deal with this problem?有哪些选择可以解决这个问题?

You can still fix a size (both width and height) to the img block and use the css property object-fit: contain;您仍然可以将大小(宽度和高度)固定到img块并使用 css 属性object-fit: contain; to keep your aspect ratio within that fixed block size.将纵横比保持在该固定块大小内。

I know it's not always the best solution, sometimes we want the img block to have the exact size of the rendered image (in that case a fixed div as a parent and min/max values does the job, but I don't know if lighthouse still shows the warning)我知道这并不总是最好的解决方案,有时我们希望 img 块具有渲染图像的确切大小(在这种情况下,固定 div 作为父级和最小/最大值可以完成这项工作,但我不知道是否灯塔仍然显示警告)

Hi @GermanProgrammer99,嗨@GermanProgrammer99,

You have to pass the width and height of the image to the image like below.您必须将图像的宽度和高度传递给如下图像。 You don't have to pass it in pixels.您不必以像素为单位传递它。

$image = get_sub_field('image');
?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['title']; ?>" title="<?php echo $image['title']; ?>" width="<?php echo $image['width']; ?>" height="<?php echo $image['height']; ?>">

If you are using a WordPress website and custom templates, you can easily do it by getting the image width and height from the image array and set them.如果您使用的是 WordPress 网站和自定义模板,您可以通过从图像数组中获取图像宽度和高度并设置它们来轻松完成。

This is just for the browser to understand the width and height that particular image occupies.这只是为了让浏览器了解特定图像占据的宽度和高度。 So that there won't be any layout shifts.这样就不会有任何布局变化。

This is the only way to do this.这是做到这一点的唯一方法。 If you are using SVG image, then you have to do some work to get the width and height of the SVG image as WordPress doesn't see SVG as an image. If you are using SVG image, then you have to do some work to get the width and height of the SVG image as WordPress doesn't see SVG as an image.

Let me know if you need more help on this.如果您需要更多帮助,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM