Most of you will see the following snippet of CSS:

#menus > li { font-size: 14px; }Copy the code

We might imagine that the browser matches the rules above from left to right. We would imagine that the browser first finds an element with a unique ID called Menus, and then applies the pattern to its immediate descendant, Li. That seems to be pretty efficient.

But, in fact, CSS selectors are matched from right to left. Therefore, this rule is not efficient; the browser must iterate over every Li element on the page and determine whether the parent has the ID of either.

The style system matches rules left from the right-most selector. If there are other selectors to the left of the current one, the style system continues to move to the left until it finds an element that matches the rule, or exits because of a mismatch. Writing Efficient CSS in Mozilla UI by David Hyatt

Here’s David Hyatt’s guide to writing efficient selectors:

1. Avoid wildcard rules

In addition to the traditional wildcard selectors, we classify the adjacent sibling selectors, child selectors, and descendant selectors into the wildcard rule classification, and recommend only ID, class, and tag selectors.

Do not qualify ID selectors

A given ID can only correspond to one element on a page, so there is no need to add additional qualifiers. For example, div#header is unnecessary and should be simplified to #header.

Do not qualify class selectors

Instead of qualifying class selectors with specific labels, extend class names as needed. For example, li.chapter would be. Li-chapter, or better yet. List-chapter.

Make the rules as specific as possible

Instead of trying to write a long selector like Ol Li a, it’s better to create a class like.list-Anchor and add it to the appropriate elements.

Avoid descendant selectors

The overhead of dealing with descendant selectors is usually highest, while using child selectors can also get the desired result and be more efficient.

Avoid tag-subselectors

If you have tag-based child selectors like # Menus > Li > A, then you should use a class to associate each tag element, such as.menus-item.

Question the full use of child selectors

Check all the places where child selectors are used, and then replace them with concrete classes if possible.

Rely on inheritance

Know which attributes can be inherited, and then avoid respecifying rules for those attributes. For example, specify list-style-image for list elements instead of each list element. Refer to the list of inherited attributes for the inheritable attributes of each element.

Excerpted from The Advanced Guide to Building High Performance Web Sites – Best Practices for Performance Optimization for Web Developers