re: Improve your CSS with these 5 principles VIEW POST

re: Nice overview - It's good to know the actual names of these tips (like "Low specificity"); that helps with remembering it :) Also, didn't realize ...

Thank you. Glad you found the article useful.

Regarding the performance studies, I am not aware of any, but if you come across any, please link them.


Generally the number of elements in a DOM is not going to be a significant performance problem to anyone (especially as its a client-side issue and thus not clogging a shared server). But, you can mess things up if you're unlucky (or really careless) so there's one trick you can use to fix nearly all performance issues:

As browsers read selectors from right to left, the right-most one is the key to good perf. Make sure it is the one that excludes most of the DOM.

eg. if you have "#myid div" as the selector, this will look through the DOM and generate a list of all the div elements, and then will look through that list (which will be many) for any that have the myid id.

if you rewrite this to be 'div #myid' then it will look through the DOM for all elements matching myid and then look through that list (of 1) to find any that are a div.

guess which is faster and more efficient.

But as mentioned, chances are you won't have any perf issues unless you have a DOM comprised several thousand repeated elements, that also have the slowest selectors (pseudo-classes or *).

It also means that many levels in your CSS isn't a problem - because they all apply to reducing scopes, if your rightmost selector produces a small set to match, then there is no problem. You can have 10 levels of CSS selector and if they rightmost one is an ID or class that matches few DOM elements, its going to be fast.


Thank you for the very detailed and insightful answer. I guessed as much regarding the performance and the worst-case scenario. In any case, I think that having a single selector is the best way to go in terms of performance, code readability and flexibility.

In any case, having several levels of CSS selectors brings up some other issues, as described in "Open/Closed principle".

code of conduct - report abuse