Fix: Cover block image sizes#78562
Conversation
|
Warning: Type of PR label mismatch To merge this PR, it requires exactly 1 label indicating the type of PR. Other labels are optional and not being checked here.
Read more about Type labels in Gutenberg. Don't worry if you don't have the required permissions to add labels; the PR reviewer should be able to help with the task. |
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message. To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. |
What?
Closes #77387
This PR dynamically calculates and overwrites the sizes attribute for Cover block background images based on the block's min-height and the image's aspect ratio. It ensures that when
object-fit: coverforces an image to scale up vertically, the browser requests an image size adequate for the rendered height rather than defaulting to a narrow rendered width.Why?
When standard or auto sizes are applied to a lazy-loaded image inside a Cover block, browsers use the layout width of the image element to determine which srcset image source to download.
However, because the Cover block uses
object-fit: coverand often enforces a rigidmin-height, a narrow Cover block container (e.g., inside a column) will clip the sides of a wide image to fulfill that height requirement. This means the layout width is small, but the image is actually scaled up significantly to match the height. The browser mistakenly downloads a low-resolution thumbnail, resulting in highly pixelated, blurry background images on both desktop layouts and mobile viewports.How?
In the PHP render callback for the Cover block, we intercept the image rendering logic (for both standard uploaded background images and Featured Images), there we calculate the aspect ratio of the image and dynamically set the sizes for the images.
This is an initial proof of concept to align on the architectural approach. Once the reviewers confirm this implementation path is correct, I will follow up by adding the corresponding tests as needed.
Testing Instructions
Screenshots or screencast
Before
cover-block-image-sizes.mov
After
cover-block-image-sizes-fix.mov
Use of AI Tools
I used Gemini 3.5 Flash to draft and format this Pull Request description based on the codebase changes provided.