CSS selector and performance

CSS selector and performance

Author: emre CSS

Poor selector intent can affect your website’s rendering time, this will result in slow load times for your website.

This is critical to keep in mind as page load time is one of Google’s highest ranking factors.

However, this is a common error as very few of programmers fully understand how browsers read CSS codes.

What do you think when you look at header ul li a { ... }?

Consider, the browser has to examine 4 elements:

  1. Find the header element
  2. then the ul element
  3. then the li element
  4. then, finally, the a element

That seems correct, right? WRONG!

Browsers do not read the way we read them (left-to-right). They read CSS codes right-to-left. That’s how browsers read header ul li a { ... } CSS code:

  1. Find the a element
  2. then the li element
  3. then the ul element
  4. then, finally, the header element

If your HTML has 50 links (a elements), header ul li a { … } CSS code selects all of those 50 a elements. CSS will then select a elements contained in li elements.Then it will select a elements within li elements, which are themselves contained in ul elements.Only then will CSS select the a elements within li elements within ul elements that are contained in header elements. Yep. We’ve gone full Inception here.

You should avoid this. Because it will make your website load slower.

What’s the solution?

It’s simple. Use BEM or target CSSing. With target CSSing, you simply give a class to your key element instead of using element … in an element selector.

Wrong way: the key selector in the CSS code below is a element: header ul li a { color:#333; text-decoration: none; }

Right way: Give a class to your key element and target that element in your CSS: .list-link { color:#333; text-decoration: none; }


Write a comment

WHO AM I?
Emre Rothzerg

Strategist.
Tech Lead.
Digital Marketer.

FOLLOW:
CONTACT:
[email protected]
HAVE A QUESTION?
JOIN NOW