I'm currently trying to improve the Lighthouse score for my website. The biggest problem that Lighthouse shows is that I don't use an explicit width and height for my images. 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?
CodePudding user response:
You can still fix a size (both width and height) to the img
block and use the css property 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)
CodePudding user response:
Hi @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.
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.
Let me know if you need more help on this.