How Can I Implement Aspect Ratio Boxes for Embeds and Iframes to Resolve "CLS Issue: More Than 0.1 (Mobile)" on My Website?

Summary

Resolving "CLS issue: more than 0.1 (mobile)" on a website involves providing space for embeds and iframes to prevent layout shifts. One technique is to use aspect ratio boxes. This method implies that you specify the width and the height properties in a ratio that reserves the required space for the element. It results in improved overall Cumulative Layout Shift (CLS) score, thus enhancing the user experience and Google's perception of the webpage's performance.

Creating Aspect Ratio Boxes

What are Aspect Ratio Boxes?

Aspect ratio boxes are a responsive CSS solution to fix layout shifts by giving an element a specified width-to-height ratio. It's particularly useful for embeds and iframes, as they often cause CLS issues when they don't have allocated space on a page [Creating Intrinsic Ratios for Video, 2020].

How to Implement Aspect Ratio Boxes

In CSS, aspect ratio boxes function by using padded boxes with a top or bottom padding representing a percentage of the width of the box. This creates a box with an aspect ratio consistent with the percentage used. You use the "padding-top" property to apply this padding. Here's how you implement aspect ratio boxes:

<div class="aspect-ratio-box">
<iframe src="your-iframe-source.com"></iframe>
</div>

<style>
.aspect-ratio-box {
position: relative;
width: 100%;
padding-top: 56.25%; /* For a 16:9 aspect ratio */
}
.aspect-ratio-box iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>

Using CSS Aspect Ratio Property

Aspect Ratio Property Concept

While aspect ratio boxes can solve the CLS issues, a newer, more elegant CSS solution is available. The `aspect-ratio` CSS property sets a preferred aspect ratio for the box, which will be used in the calculation of auto-sized lengths [aspect-ratio, 2021].

Implementation with aspect-ratio Property

Here's an example of how you can use the `aspect-ratio` property:

<style>
iframe {
aspect-ratio: 16 / 9;
width: 100%;
height: auto;
}
</style>
This CSS would ensure all your iframes on your site maintain a 16:9 ratio and adjust their height automatically.

Conclusion

CLS issues triggered by embeds and iframes can be mitigated using aspect ratio boxes or the CSS `aspect-ratio` property. Implementing these methods can enhance the user experience and boost your site's CLS score.

References