Performance concerns with the :has() selector
understanding of selector matching cost.
:has() forces upward and forward style invalidation on DOM changes, broad subjects are costly; mitigate by scoping the subject, avoiding deep or universal arguments, and limiting dynamic…
WHAT THIS TESTS: This checks that you understand the engine's style invalidation model and why relational selectors complicate it, plus concrete mitigation tactics.
A GOOD ANSWER COVERS: Normal selectors match an element from its own attributes and ancestors, which the engine can invalidate efficiently. Because :has() matches based on descendants or following siblings, a change deep in the tree can affect whether an ancestor matches, so the engine must invalidate and recompute styles upward and across siblings. The cost grows with how broad the subject is, how deep or unbounded the relative selector is, and how often the relevant subtree mutates. Mitigations include anchoring the subject to a specific, narrow selector instead of a tag or universal, keeping the inner relative selector shallow and specific, avoiding the universal selector inside :has(), and limiting :has() to regions that rarely change rather than high-frequency interactive areas. Modern engines optimize common cases, but you should still measure on large, dynamic pages.
COMMON WRONG ANSWERS: Saying :has() has the same cost as any other pseudo-class. Putting :has(*) or very deep descendant chains across the whole document. Using it on rapidly updating lists without considering invalidation churn. Assuming the browser will optimize away all overhead.
LIKELY FOLLOW-UPS: How does style invalidation differ from layout and paint cost. How do browsers bucket and optimize :has() in practice. When would you prefer toggling a class via JavaScript instead.
ONE CONCRETE EXAMPLE: Replace a broad body:has(.modal-open) that revalidates on every mutation with a tighter .app-shell:has(> .modal-open), anchoring the subject and bounding the relationship to a direct child, so the engine only re-checks a small, stable region when a modal opens.
Read the original → developer.mozilla.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.