Hi,
I totally understand the issue you’re facing with Cumulative Layout Shift (CLS) for the dynamic hero image. It can be frustrating, especially when you’re trying to optimize your site’s performance for Google. Fortunately, there’s a simple solution that will allow you to set a placeholder image while the hero image is loading, even with the dynamic sizing based on the device.
Use Aspect Ratio for Placeholder Image
To prevent the layout shift, you can create a placeholder element with a set aspect ratio that will maintain the same space on the page while the dynamic hero image loads. This approach ensures that the layout stays consistent, even on different screen sizes.
Step-by-Step Solution with Code:
Use a div block to act as a placeholder, but instead of giving it a fixed size, we’ll use a CSS aspect ratio so that it scales responsively based on the hero image’s aspect ratio.
Since your hero image is dynamically sized, use the padding-top trick to control the aspect ratio. This method works by setting the padding to a percentage value, which makes the div block responsive.
![Hero Image]()
.hero-placeholder {
width: 100%; /* Make the placeholder responsive */
padding-top: 56.25%; /* 16:9 aspect ratio (adjust to your image’s aspect ratio) */
background-color: #f0f0f0; /* Set a background color for the placeholder */
}
.hero-image {
width: 100%;
height: auto;
display: block;
}
After applying these changes, be sure to check your site’s performance again on Google PageSpeed Insights to see the impact on CLS score.
Alternatively, if you don’t want to spend too much time on optimization, you can try our Website Speedy tool, which offers a 14-day free trial. It automatically handles the optimization for you, saving you time and effort.
(Disclaimer: We are the developers of this tool and are happy to answer any questions you may have.)