July 5, 2016 Log No. 731

Do You Even CSS Bro?

Apparently I don’t. Because while I pride myself on having a long and relatively uncontentious (I actually like it!) history with CSS, and an above-average (if I do say so myself) knowledge of selectors and props, I never thought about efficiency. Til I came across this article:

Writing Efficient CSS
(written in 2000. So when I was 10. Wish I’d come across it then…)

Now in age of minifiers and preprocessors, maybe a lot of this efficiency stuff isn’t going to make a huge difference. And in fact, even the underlying browser engine has changed enough that CSS rendering is not really an issue. (See CSS Selector Performance has Changed!.) But still, these are good principles to keep in mind and the sad thing is, all of them were news to me. Even basics such as:

  • CSS matches selectors right to left. You know, that makes a lot of sense now that I think about it.
  • So with that being said, avoid unnecessary rules–if you have a very specific id or class, just use that as the selector. Don’t attach a tag element as well–that’s minimally better specificity and slower filtering performance.
  • Avoid descendent selectors because they are the most expensive selectors in CSS. Wow I feel super guilty; this is by far my biggest sin. As the article points out, usually you want the child selector (>) anyway. I mean, it’s not wrong…but I always thought the child selector looked ugly…*shame*
  • …But also avoid child selector if you can. Additional rule filtering == expensive == bad!

So it really all triple-underlines the main moral of the story: have as few selectors as you can. Favor having a super specific class or id like ul-header-blue than nesting a lot of selectors. I get that’s what some of the big CSS frameworks like BEM go for, but I guess I always thought it was for maintainability, not also for efficiency. TIL…just 16 years later.

Leave a Reply

Your email address will not be published. Required fields are marked *