CSS more efficient

Sararellano
2 min readMar 23, 2021
CSS Efficient

I have to be honest: I didn’t think about how efficient my CSS is. I focus more on trying to make my JS code more efficient so that the browser renders it as soon as possible, but I had never looked at my CSS. So I started to find information about how to make more efficient CSS code and I would like to share with you my investigation:

Selector types

There are 4 selector types: ID, classes, tags and globals. They are ordered according to how efficient they are.

#btn — submit {} /* ID (fastest) */body .main #faq {} /* ID */.main {} /* Class */ul li a.btn — primary {} /* Class */div {} /* Tag */div ul li {} /* Tag */*{} /* Global (slowest) */

This is because browsers read CSS from right to left, so, for example in `ul li a.btn — primary` they search first all a.btn — primary and then if they are inside a li and then, if they are inside an ul. This is why div #btn — share is fastest than #btn — share div

About that, it’s important to say that if a selector doesn’t match with anything, it is not going to waste energy because as soon as a match fails, the browser stops trying.

Descendant selector

A descendant selector is very expensive, and even more so if it contains a tag or a global selector. So don’t use them.

html body div a {}

Don’t tag an ID

IDs are unique, you can’t have 2 IDs with the same name, so they don’t need a tag with them. If you make it, you will make the ID less efficient:

button#btn — share {}

#btn — share

If you can avoid doing it with classes, don’t do it too. Classes are not unique, so maybe you need to add a tag, but if you can, avoid it.

Properties

Some CSS properties are heavier and expensive than others.

border-radiusbox-shadowfilterposition: fixedtransform

I don’t say that you can’t use them, but use them with moderation and if you can, choose an alternative option.

To end, these hacks are important, but be careful, because it’s more important to take care of semantic, maintainability and legibility than a little microsecond of efficiency.

Resources

I found some interesting pages while writing this article.

  • https://csstriggers.com/ : this page collects all properties in alphabetical order, and lets you know whether changing their values will trigger layout, print or composite work. You can click on a property and see more detailed information about what the costs might be and what will happen.
  • https://github.com/uncss/uncss : a tool that remove all useless CSS
  • https://flukeout.github.io/ : a game to learn CSS selectors

--

--