Reputation: 1523
When I have read about faster css selectors, I have notice IDs
and Classes
are faster than any other. Also, browsers match your CSS Selectors
from Right to Left. That is, the most specific selector first.
So the author said Do not attach any descendents to the classes; IDs.
However, when I have read the source code of Facebook and Twitter, I have found them using CSS this way: .uiInfoTable .label .annotation{color:#999}'
, .big-photo-permalink .tweet .tweet-timestamp{// some css}
When these selectors are slow, why don't they simply use .annotation{color:#999}
instead of such a long selector, or if the class is available to both tags, then why not create a new class and add those CSS?
Is there anything I should know about descendent selectors? Do they have impact on performance of CSS selectors?
Upvotes: 0
Views: 164
Reputation: 324620
In most cases, the performance hit is practically zero. However if you start building more complex stylesheets, that "almost zero" can add up to something quite big.
Personally, I like to use the >
combinator whenever I can. .menu>li
is better than .menu li
for example because the engine only has to look up one level instead of going all the way to the top every time.
Another upside of >
is that it's clearly-defined. Imagine this:
<ul class="nav">
<li>Item 1</li>
<li>Item 2</li>
<li>Item with submenu
<ul>
<li>Item 3.1</li>
<li>Item 3.2</li.
</ul>
</li>
</ul>
Now let's say you want to apply a style to <li>
s, but not the submenu. .nav>li
works beautifully for this, whereas .nav li
will style submenus too. An ignorant programmer might try to override it back with .nav li li
, making the performance problem worse.
Upvotes: 1