Use efficient CSS selectors

This article was first published on CSS-101 (02-07-2011).

Using descendant selectors is inneficient, but when your key selector (the rightmost selector) is a ID selector, then things get worse.

Consider the following rule (and remember that IDs are unique): #nav li ul li a#active {...}

Since browsers read the above from right to left, this is how it goes from their perspective:

The rule says, go fetch!
First check: #nav li ul li a#active
The browser goes:
I found it! I found it! :-)
The rule says, keep fetching...
Second check: #nav li ul li a#active
The browser goes:
Yes, I found it already!
The rule says, keep fetching...
Third check: #nav li ul li a#active
The browser goes:
I said I found it! Didn't I say I found it?
The rule says, keep fetching...
Fourth check: #nav li ul li a#active
The browser goes:
Helloooo! Anybody there? I said I found it!
The rule says, keep fetching...
Fifth check: #nav li ul li a#active
The browser goes:
You must be kidding me. I said I FOUND IT!!
The rule says, keep fetching...
Last check: #nav li ul li a#active
The browser goes:
WTF!? WHAT DON'T YOU UNDERSTAND IN "I FOUND IT"!

On a more serious noteā€¦

Share