Hacker News new | ask | show | jobs
by jacobwilliamroy 3021 days ago
Generally you would want to avoid descendant and child selectors. With rules like

  ul > li > a

  .selector .selector1 li a
The system will check ALL anchor tags and move left until it has completely matched the rule. This makes the above selectors extremely expensive (perfomance-wise) and can cause slow page-loads. Tag selectors and universal selectors are generally a bad idea for this same reason.

And using inheritance to select elements indirectly is actually better for performance than directly selecting the inheriting elements. For example, if you want to set typography for an entire page, instead of selecting all p and h1 tags, just select the body tag.

Here's a link to a more in-depth explanation of all of the above with examples:

http://mdn.beonex.com/en/CSS/Writing_Efficient_CSS.html

1 comments

The good news is all modern browsers use a Bloom Filter to quickly skip over elements that wouldn't match the descendant or child selector relationship.

You could probably construct situations with very deep selector relationships and thousands of matching elements where the ancestor walking adds up but the other costs of computing style often end up being more important than the selector matching in many scenarios. Not that you shouldn't aim for simpler selectors of course.

(Usually the problems with expensive selectors come from side effects of dynamic changes to the document. ex. Some selectors will make the browser recompute hundreds of elements when only changing something small because the browser isn't tracking that relationship in a precise way.)

Hmm so what’s consensus then? Avoid these types of selectors when at all possible or no?