I'm trying to make a Wordpress theme and I'm very confused about how I should use responsive images. Here's how I'm currently displaying each thumbnail in my post list:
<? the_post_thumbnail() ?>
The output is:
<img
width="2560"
height="1710"
src="https://wordpress.local/wp-content/uploads/2022/11/photo-scaled-1.jpg"
class="attachment-post-thumbnail size-post-thumbnail wp-post-image"
alt=""
decoding="async"
loading="lazy"
srcset="
https://wordpress.local/wp-content/uploads/2022/11/photo-scaled-1.jpg 2560w,
https://wordpress.local/wp-content/uploads/2022/11/photo-scaled-1-300x200.jpg 300w,
https://wordpress.local/wp-content/uploads/2022/11/photo-scaled-1-1024x684.jpg 1024w,
https://wordpress.local/wp-content/uploads/2022/11/photo-scaled-1-768x513.jpg 768w,
https://wordpress.local/wp-content/uploads/2022/11/photo-scaled-1-1536x1026.jpg 1536w,
https://wordpress.local/wp-content/uploads/2022/11/photo-scaled-1-2048x1368.jpg 2048w
"
sizes="(max-width: 2560px) 100vw, 2560px"
/>
And it renders like this:
Each thumbnail is (currently) 430x275 px, so I would expect the 768x513 version of the image to be displayed. However, when I hover the image, Chrome says the "current version" is the "1536x1026" version:
This is unnecessarily large, and Lighthouse yells at me for showing improperly scaled images:
So how do I fix this? I just want to render the image and have the browser pick the most appropriate source for the current image size.
I assume this is because the sizes
attribute is set to 100vw
, which causes the browser to always show an image that is larger than the current viewport width (or 2560px). Can I customize this?
If I choose to render a specific size, for example: <? the_post_thumbnail("thumbnail") ?>
, then Wordpress doesn't render the srcset
or sizes
attribute at all, completely breaking responsiveness.
I feel like I'm missing something obvious. How am I supposed to:
- Render a post thumbnail, having the browser pick the smallest possible source that fits the image size
- Also render
srcset
so the browser can choose a higher resolution image on high-resolution displays