Reputation: 2782
I want to set a responsive image in my webpage using tailwind css. I have provided sufficient classes to make it work on different screen sizes. Now I am getting the following error in page-speed.
How can I eliminate the warning?
Upvotes: 4
Views: 6825
Reputation: 6185
First determine the dimensions of the original image - either by looking at the original image you're pulling in or by seeing what size it renders at using browser dev tools. The dimensions themselves aren't important because the browser uses them to calculate an aspect ratio. Add these dimensions using width
and height
attributes, and then add the img-fluid
class to the image:
<img src="..." class="img-fluid" width="300" height="300" />
Upvotes: 1
Reputation: 6422
This warning exists to prevent layout shift when images load. Currently, the images have the classes w-5/6 mx-auto
. This is enough to make the images responsive, but before the images are loaded, the browser doesn't know how tall the image is. Hence, when the image loads, there will be layout shift.
You then need to tell the browser how wide and tall the image should be before it loads. There a few ways of doing this.
If you know the height of the image, I'd recommend following fromaline's answer.
<img src='assets/image/brainstorm.svg' alt='nature' class='w-5/6 mx-auto border' width='300' height='300' />
Because we've defined the display width with w-5/6
, the image will be responsive. The width='300'
and height='300'
properties are then used for the aspect ratio.
Here's a link from the Tailwind playground to show you how it's both responsive and removes layout shift: https://play.tailwindcss.com/rjz9ylFNl5?size=482x720
If you don't know the width and height of your images and you need them to be responsive, you need to essentially create a container with a fixed aspect ratio. I'd recommend looking at the aspect ratio plugin.
<div class='w-5/6 aspect-w-16 aspect-h-9 mx-auto'>
<img src='assets/image/brainstorm.svg' alt='nature' class='object-cover w-full h-full' />
</div>
Again, a link to a Tailwind Playground demo: https://play.tailwindcss.com/2zmPJixbrO?size=584x720
Upvotes: 1
Reputation: 605
Just adding height and width attributes and classes won't work, you have to crop the images as well to its exact dimension. For example if you have set 100px height and width, the image height and width should also be 100px.
Upvotes: 0
Reputation: 527
You can eliminate this warning by adding width
and height
to your images like this:
<img loading="lazy" src="assets/image/brainstorm/svg" alt="brainstorm" width="400" height="200" class="w-5/6 mx-auto" />
Basically adding width
and height
directly to html img
tag prevents layout shifts, even if img
is not loaded yet. It's especially important when img
is lazy-loaded. More info here
Upvotes: -1