Optimize Cumulative Layout Shift (CLS)

The Cumulative Layout Shift is the metric that checks for the moving elements while the content is painted on the screen. Too much layout shift will affect user experience hence it is important to keep visual stability. 

Most common issues:

  • Avoid large layout shifts
  • Avoid non-composited animations
  • Image elements have explicit width and height

In case of images, you just need to set the final dimensions needed. Something like this:

<img width=“267” height=“400” src=”dog.jpg”>

For a normal elements like boxes, or containers it can happen if you set lesser dimensions and after some triggers on page load if it grows then it will cause “Layout” again for the same element. It is also called “DOM Reflow” because browser repaints elements. While doing this the screen flickers or moves. 

Consider a scenario where you have a box initially set to 100×100 pixels. 

While page is loadingAfter the page loads
.box {  width: 100px;  height: 100px;}.box {  width: 200px;  height: 200px;}

But then some javascripts or external resources load the style or dynamically sets the styles to set it to 200×200 pixels. 

In such cases it is important to set the styles which are eventually needed to avoid such reflow, or layout. 

You can simply set the final dimensions required in the CSS file or inline the CSS in head or even on the element itself. That will prevent the CLS issues.

Resources:

Watch this video tutorial for better understanding

Quizzes