CSS performance

The descendant selector can be expensive

Depending on how large your application is, only using the descendant selector without more specificity can be really expensive. The browser is going to check every descendant element for a match because the relationship isn’t restricted to parent and child.

For example:

Example of descendant selector

The browser is going to assess all the links on the page before settling to the ones actually inside our #nav section.

A more performant way to do this would be to add a specific selector of .navigation-link on each <a> inside our #nav element.

The browser reads selectors from right to left

I feel like I should have known this one because it sounds essential, but I didn’t…

When parsing CSS, the browser resolves CSS selectors from right to left.

If we look at the following example:

The browser reads from right-to-left

The steps taken are:

match every <a> on the page.

on the page. find every <a> contained in a <li> .

contained in a . use the previous matches and narrow down to the ones contained in a <ul> .

. Finally, filter down the above selection to the ones contained in an element with the class .container

Looking at these steps, we can see that the more specific the right selector is, the more efficient it will be for the browser to filter through and resolve CSS properties.

To improve the performance of the example above, we could replace .container ul li a with adding something like .container-link-style on the <a> tag itself.

Avoid modifying layout wherever possible

Changes to some CSS properties will require the whole layout to be updated.

For example, properties like width , height , top , left (also referred to as “geometric properties”), require the layout to be calculated and the render tree to be updated.

If you change these properties on a lot of elements, it’s going to take a long time to calculate and update their position/dimension.

Be careful of paint complexity

Some CSS properties (e.g: blur) are more expensive than others when it comes to painting. Think about potential other more effective ways to achieve the same result.

Expensive CSS properties

Some CSS properties are more expensive than others. What this means is that they take longer to paint.

Some of these expensive properties include:

border-radius

box-shadow

filter

:nth-child

position: fixed

It doesn’t mean you shouldn’t use them at all but it’s a matter of understanding that if an element uses some of these properties and will render hundreds of times, it will impact the rendering performance.