๐ Instructions
In this hands-on exercise, you will learn how to measure and optimize the Cumulative Layout Shift (CLS) metric using browser DevTools.
๐ What is CLS?
Cumulative Layout Shift (CLS) measures the sum of all unexpected layout shifts that occur during the entire lifespan of a page. A layout shift occurs any time a visible element changes its position from one rendered frame to the next.
โก Demo Section (with CLS Issues)
Experiencing Layout Shift
The content below has intentional layout shift issues. Watch what happens as resources load:
Some initial content that will shift around...
This is an advertisement that loads late!
It doesn't have reserved space.
This text will shift down when the ad appears above it. Try scrolling or clicking the button below to trigger the shift!
Optimized Version (No CLS)
Here's the same content with proper optimization to prevent layout shifts:
Some initial content with proper spacing...
This is an advertisement with reserved space!
It loads in a space we set aside for it.
This text won't shift because we've reserved space for the ad above.
CLS Measurements
๐งช Measuring CLS
- ๐ ๏ธ Open the browser DevTools by pressing
F12
orCtrl+Shift+I
(Windows/Linux) orCmd+Opt+I
(Mac). - ๐ Navigate to the "Performance" tab.
- ๐ Click the "Reload" button (circular arrow) to start recording and reload the page.
- ๐ Try clicking the "Trigger Layout Shift" button during recording.
- โฑ๏ธ After the page loads and shifts occur, stop the recording.
- ๐ Look for the red rectangles in the "Experience" section, which indicate layout shifts.
- ๐ Click on these layout shift markers to see details about the affected elements.
- ๐ Check the "Layout Shift Regions" in the filmstrip view (colored rectangles appear where shifts occurred).
๐ ๏ธ Common CLS Optimization Techniques
- ๐ Reserve space for dynamic content: Always specify width and height attributes for images, videos, embeds and ads.
- ๐ Use proper containing boxes: Wrap elements that can change size in containers with defined dimensions.
- โก Avoid inserting content above existing content: Add new content below the viewport or in areas that won't displace existing content.
- ๐ Use web font loading strategies: Implement
font-display: optional
or preload important fonts. - ๐ผ๏ธ Use aspect ratio boxes: For responsive media, use modern CSS aspect-ratio property or padding-top technique.
- โณ Transform animations: Use CSS transforms instead of properties that trigger layout changes.
๐งโ๐ป Try It Yourself!
Use the DevTools Elements panel to fix the layout shift in the problem demo:
- Add a fixed height to the
.late-load-ad
element - Set
min-height
to reserve space - Reload and observe the improvement in CLS