CSS techniques to optimize Web Vitals

A Kravets

The way you write your style and build your layout can make a big difference Core Network Vitalers. This is especially true Cumulative Layout Change (CLS) and Maximum Content Goal (LCP).

This article discusses CSS techniques for optimizing Web Vitals. These optimizations are broken down by different aspects of the page: layout, images, fonts, animations, and loading. Along the way, we explore example page:

Screenshot of an example site

Layout #

Adding content to the DOM #

Adding content to a page after the surrounding content has already been loaded pushes everything else on the page down. this causes the layout changes.

Cookie notifications, especially those placed at the top of the page, are a common example of this problem. Other page elements that often cause this kind of layout change when loading are ads and embeds.

Recognise #

The lighthouse’s “Avoid major layout changes” inspection identifies shifted page elements. The results of this presentation look like this:

Lighthouse 'Avoid major layout changes' inspection

The cookie notification is not listed in these observations because the cookie notification itself does not change during download. Rather, it causes items below the page (i.e. div.hero and article) to change. For more information on identifying and correcting layout changes, see Debugging layout changes.

The beacon analyzes the page’s performance up to the “page load” event. Cookie banners, ads, and other widgets sometimes load only after the page has loaded. These layout changes will continue to affect users, even if they are not marked by Lighthouse.

Fix #

Place a cookie notification at the bottom of the page using an absolute or fixed location.

A cookie message is displayed at the bottom of the page

Before:

.banner {
position: sticky;
top: 0;
}

After:

.banner {
position: fixed;
bottom: 0;
}

Another way to fix this layout change would be to reserve space for a cookie notification at the top of the screen. This approach is just as effective. See more information Cookie notification best practices.

A cookie notification is one of many page elements that trigger layout changes when loaded. We help us to get to know these page elements in more detail, there is no cookie notification in the later stages of the presentation.

Pictures #

Images and Maximum Content Paint (LCP) #

Images are usually the largest content paint (LCP) element on a page. Other side elements, which can be LCP elements includes blocks of text and video poster images. The time the LCP element loads determines the LCP.

It is important to note that the LCP element of a page may vary depending on the page load, the content that is visible to the user when the page is first displayed. For example, in this presentation, the cookie bulletin background, hero image, and article text are some potential LCP elements.

A diagram that highlights the LCP element of a page in different situations.

On the example site, the cookie notification wallpaper is actually a big picture. To improve LCP, you can paint a gradient in CSS instead of uploading an image to create an effect.

Fix #

Change .banner CSS uses a CSS gradient instead of an image:

Before:

background: url("https://cdn.pixabay.com/photo/2015/07/15/06/14/gradient-845701_960_720.jpg")

After:

background: linear-gradient(135deg, #fbc6ff 20%, #bdfff9 90%);

Images and layout changes #

Browsers can only set the image size when the image loads. If the image loads after the page is rendered, but no space is reserved for the image, the layout change occurs when the image appears. In the demo, the hero image causes the layout to change as it loads.

The phenomenon of images that cause a change in layout is more pronounced in situations where images load slowly — for example, over a slow connection or when loading an image with a particularly large file size.

Recognise #

Recognizes images without explicit width and height, use the Lighthouse “Pixels have specific width and height” check.

The lighthouse's 'Picture Elements have specific width and height' inspection

In this example, both the hero image and the article image are missing width and height attributes.

Fix #

Set width and height attributes of these images to avoid layout changes.

Before:

<img src="https://source.unsplash.com/random/2000x600" alt="image to load in">
<img src="https://source.unsplash.com/random/800x600" alt="image to load in">

After:

<img src="https://source.unsplash.com/random/2000x600" width="2000" height="600" alt="image to load in">
<img src="https://source.unsplash.com/random/800x600" width="800" height="600" alt="image to load in">

The image will now be loaded without changing the layout.

Another way to download images is to use srcset and sizes attributes together with the definition width and height attributes. This has the added performance advantage of allowing you to display images of different sizes for different devices. See more information Show sensitive images.

Fonts #

Fonts can delay text rendering and cause layout changes. This is why it is important to deliver fonts quickly.

Delayed text rendering #

By default, the browser does not render the text element immediately if the associated web fonts have not yet been loaded. This is done to prevent a “Stylish Text Flash” (FOUT). In many situations, this is delayed First Content Goal (FCP). In some situations, this delays the maximum content goal (LCP).

By default, Chromium-based and Firefox browsers do prevent text from being rendered for up to 3 seconds if the associated web font is not loaded; Safari prevents text from being rendered indefinitely. blocking time starts when the browser requests the network font. If the font is still not loaded by the end of the blocking period, the browser will render the text on the spare disk and change the network font when available.

Layout changes #

While changing fonts is great for displaying content to the user quickly, it can cause layout changes. These layout changes occur when a web font and its alternate font take up a different amount of space on a page. Using similar fonts minimizes the size of these layout changes.

A diagram showing the layout change caused by a font change
In this example, changing the font caused the page elements to move up by five pixels.

Recognise #

To see the fonts that can be downloaded to a specific page, open Network tab in DevTools and filter Font. Fonts can be large files, so using only fewer fonts usually has better performance.

Screenshot of the font displayed in DevTools

To see how long it takes to request a font, click Timing tab. The faster the font is requested, the faster it can be downloaded and used.

Screenshot of the DevTools Scheduling tab

To see the font request chain, click Beginner tab. In general, the shorter the request chain, the faster the font can be requested.

Screenshot of the DevTools Initiator tab

Fix #

This demo uses the Google Fonts API. Google Fonts offers the ability to download fonts <link> tags or @import opinion. <link> the code snippet contains a preconnect resource tip. This should lead to a faster delivery of the stylesheet than @import version.

You can think at a very high level resource tips as a way to imply to the browser that it needs to establish a certain connection or download a certain resource. As a result, the browser prioritizes these actions. When using resource hints, keep in mind that prioritizing a particular feature removes browser resources from other features. Therefore, resource tips should be used judiciously and not for everything. See more information Establish network connections early to improve page speed.

Delete the next one @import expression from your stylesheet:

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400&family=Roboto:wght@300&display=swap');

Add the following <link> tags <head> document:

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap" rel="stylesheet">

These link tags direct the browser to make an early connection to the origin used by Google Fonts and load a stylesheet that includes the Montserrat and Robot font notification. These <link> Tags should be placed already <head> as much as possible.

If you only want to download a subset of fonts from Google Fonts, add ?text= API parameters. For example, ?text=ABC load only the characters necessary to render “ABC”. This is a good way to reduce the font file size.

Animations #

The primary way animations affect Web Vitals is when they cause layout changes. There are two types of animations that you should avoid: animations that trigger the layout and “animation-like” effects that move side elements. These animations can typically be replaced with more powerful equivalents by using CSS features such as transform, opacityand filter. See more information How to create high performance CSS animations.

Recognise #

The Lighthouse “Avoid Unconnected Animations” audit can be helpful in identifying animations that have not performed.

Lighthouse's 'Avoid unconnected animations' check

Warning:

The Lighthouse “Avoid Unconnected Animations” inspection only identifies non-performing ones CSS animations; JavaScript-based animations (e.g. setInterval() element “to animate”) are poor for performance, but this check does not mean them.

Fix #

Change slideIn animation series to use transform: translateX() rather than movingmargin-left property.

Before:

.header {
animation: slideIn 1s 1 ease;
}

@keyframes slideIn {
from {
margin-left: -100%;
}
to {
margin-left: 0;
}
}

After:

.header {
animation: slideIn 1s 1 ease;
}

@keyframes slideIn {
from {
transform: translateX(-100%);
}

to {
transform: translateX(0);
}
}

Critical CSS #

Style sheets prevent rendering. This means that when a browser encounters a stylesheet, it stops loading other resources until the browser has downloaded and parsed the stylesheet. This can delay the LCP. Consider improving performance removing unused CSS, critical CSSand postponing non-critical CSS.

Conclusion #

Although further improvements (e.g. picture compression to deliver images faster), these changes have significantly improved the Web Vitals service on this site. If this were a real site, the next step would be collect performance data from actual users to evaluate it Meeting Web Vitals thresholds for most users. For more information on Web Vitals, see Learn Web Vitals.

Last updated: Improve the article

LEAVE A REPLY

Please enter your comment!
Please enter your name here