
Reduce the Complexity of CSS Selectors
May 7, 2025About 2 min
Reduce the Complexity of CSS Selectors 관련
The Front-End Performance Optimization Handbook – Tips and Strategies for Devs
When you’re building a website, you’ll want it to be responsive, fast, and efficient. This means making sure the site loads quickly, runs smoothly, and provides a seamless experience for your users, among other things. So as you build, you’ll want to...
The Front-End Performance Optimization Handbook – Tips and Strategies for Devs
When you’re building a website, you’ll want it to be responsive, fast, and efficient. This means making sure the site loads quickly, runs smoothly, and provides a seamless experience for your users, among other things. So as you build, you’ll want to...
1. When browsers read selectors, they follow the principle of reading from right to left.
Let's look at an example:
#block .text p {
color: red;
}
- Find all P elements.
- Check if the elements found in result 1 have parent elements with class name "text"
- Check if the elements found in result 2 have parent elements with ID "block"
Why is this inefficient? This right-to-left evaluation process can be very expensive in complex documents. Take the selector #block .text p
as an example:
- The browser first finds all
p
elements in the document (potentially hundreds) - For each of those paragraph elements, it must check if any of their ancestors have the class
text
- For those that pass step 2, it must check if any of their ancestors have the ID
block
This creates a significant performance bottleneck because:
- The initial selection (
p
) is very broad - Each subsequent step requires checking multiple ancestors in the DOM tree
- This process repeats for every paragraph element
A more efficient alternative would be:
#block p.specific-text {
color: red;
}
This is more efficient because it directly targets only paragraphs with a specific class, avoiding checking all paragraphs
2. CSS selector priority
Inline > ID selector > Class selector > Tag selector
Based on the above two pieces of information, we can draw conclusions:
- The shorter the selector, the better.
- Try to use high-priority selectors, such as ID and class selectors.
- Avoid using the universal selector.
Practical advice for optimal CSS selectors:
/* ❌ Inefficient: Too deep, starts with a tag selector */
body div.container ul li a.link {
color: blue;
}
/* ✅ Better: Shorter, starts with a class selector */
.container .link {
color: blue;
}
/* ✅ Best: Direct, single class selector */
.nav-link {
color: blue;
}
Finally, I should say that according to the materials I've found, there's no need to optimize CSS selectors because the performance difference between the slowest and fastest selectors is very small.