Quiz

Explain how a browser determines what elements match a CSS selector.

Topics
BrowserCSS

This question is related to the question about writing efficient CSS. Browsers match selectors from rightmost (the key selector) to left. Browsers filter out elements in the DOM according to the key selector and traverse up their parent elements to determine matches. The shorter the length of the selector chain, the faster the browser can determine if that element matches the selector.

For example, with a selector p span, browsers first find all the <span> elements and traverse up their parents all the way up to the root to find a <p> element. For a particular <span>, as soon as it finds a <p>, it knows that the <span> matches the selector and can stop traversing its parents.

Edit on GitHub