Sub topic 11
Keeping :has() selectors fast
This chapter assumes you can write :has() selectors with descendant, child, and sibling arguments. It also assumes you know how the cascade orders rules. You will learn what makes a :has() selector expensive, which patterns avoid the cost, and how to measure the result in your own page.
Why :has() costs more than other selectors
Most selectors look only at the element being tested and at its ancestors or earlier siblings. When you change a class on a <div>, the browser checks the rules that could apply to that <div> and its subtree.
:has() reverses the direction. The browser must look down into descendants or forward to later siblings. A change deep in the tree can change the match result of an ancestor, so the browser has to work out which ancestors need to be re-checked.
Browser engines have optimized this heavily. Ordinary selectors such as .card:has(img) are fine on normal pages. The risk comes from selectors that are broad, on large pages, with frequent DOM or state changes.
How the browser evaluates a :has() selector
The engine matches a selector from right to left. It first checks whether an element fits the subject, which is the compound selector that carries :has(). Only then does it evaluate the :has() argument against the element's descendants or following siblings.
The subject therefore decides how many elements pay for the argument check. The argument decides how far each check has to search.
Each step has a way to go wrong. Too many candidates, a long scan, or a style change that spreads to a large subtree each makes the work grow.
Rules for fast selectors
Give the subject a real name
A bare :has() or *:has() makes every element a candidate. Anchor the selector to a class, an attribute, or a specific element type.
/* Every element in the document is a candidate subject */
:has(> img) {
outline: 1px solid red;
}
/* Only .card elements are candidates */
.card:has(> img) {
outline: 1px solid red;
}Prefer the child combinator
A descendant argument such as :has(img) may have to search the whole subtree. A child argument such as :has(> img) only examines direct children. If your markup lets you say "direct child", say it.
/* Searches the entire subtree of each .list */
.list:has(a.active) { background: #f4f4f4; }
/* Checks direct children only */
.list:has(> a.active) { background: #f4f4f4; }Use the narrower form only when it expresses what you mean. If the active link can sit inside a wrapper, > a.active will silently stop matching.
Use the adjacent sibling combinator over the general one
h2:has(+ p) looks at one element. h2:has(~ ul) may look at every later sibling. Prefer + unless the target can be several elements away.
Make the argument specific
Arguments that begin with a class, an ID, or an attribute let the engine reject non-matching nodes quickly. Arguments like :has(*) or :has(:not(img)) force a test of nearly every node.
Remember from the earlier chapter that .card:has(:not(img)) means "has some descendant that is not an img". That condition is true for almost every card, so it saves no work and rarely says what you intended. If you mean "has no image", write .card:not(:has(img)).
Avoid watching the whole document without a reason
Selectors like body:has(.modal.open) or :root:has(#dark-toggle:checked) have one subject, so matching the subject is cheap. The cost sits in two other places:
- The browser must re-check the argument whenever something inside the subtree changes. For
body, that is any change anywhere. - When the match flips, styles can change for the whole page. This is often the larger cost, and it is the cost of the change itself, not of
:has().
A theme toggle runs once per click, so this is acceptable. A body:has(...) rule that depends on state changing every frame, for example during scrolling or typing, is a bad fit. Keep such state on a small container, not on body.
Comparing selectors
| Selector | Candidate subjects | Search per candidate | Notes |
|---|---|---|---|
| `:has(img)` | Every element | Whole subtree | Avoid. Name the subject. |
| `.card:has(img)` | Each `.card` | Whole subtree of the card | Fine for small cards. |
| `.card:has(> img)` | Each `.card` | Direct children | Prefer when markup allows. |
| `h2:has(~ ul)` | Each `h2` | All later siblings | Use `+` if the list is next. |
| `h2:has(+ ul)` | Each `h2` | One sibling | Cheapest sibling form. |
| `.card:has(:not(img))` | Each `.card` | Nearly every node | Rarely what you mean. |
| `body:has(.modal.open)` | `body` | Whole document | Cheap match, but re-checked after any change in the page. |
Measuring instead of guessing
Judge selector cost by measurement. The page below builds 5,000 cards and toggles a class on one of them. It then times how long the browser takes to recalculate styles under each rule set. Reading offsetHeight forces the browser to finish its style work before the timer stops.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>:has() timing</title>
<style id="rules"></style>
</head>
<body>
<div id="root"></div>
<script>
const root = document.getElementById('root');
const rules = document.getElementById('rules');
for (let i = 0; i < 5000; i++) {
const card = document.createElement('div');
card.className = 'card';
card.innerHTML = '<p>Text</p>' +
(i % 2 ? '<img alt="" width="10" height="10">' : '');
root.append(card);
}
function measure(label, css, runs = 20) {
rules.textContent = css;
void document.body.offsetHeight; // flush pending style work
const target = root.lastElementChild;
const start = performance.now();
for (let i = 0; i < runs; i++) {
target.classList.toggle('touched');
void document.body.offsetHeight; // force style recalculation
}
const avg = (performance.now() - start) / runs;
console.log(label + ': ' + avg.toFixed(3) + ' ms per change');
}
measure('no rule', '');
measure(':has(img)', ':has(img) { outline: 1px solid red; }');
measure('.card:has(img)', '.card:has(img) { outline: 1px solid red; }');
measure('.card:has(> img)', '.card:has(> img) { outline: 1px solid red; }');
</script>
</body>
</html>Open the page and read the console. Numbers differ between browsers, machines, and versions, so use them to compare selectors against each other on the same machine. Do not treat them as universal figures.
For a real page, use the browser's developer tools. Record a performance profile and look at the "Recalculate Style" entries. Chromium-based browsers can also show per-selector statistics for style recalculation, which helps you find a slow rule.
Common mistakes
- Writing
:has()with no subject. It looks harmless in a small test page and gets expensive in a large application. - Treating
:has(:not(x))as the opposite of:not(:has(x)). They test different conditions, and the first is usually broad and always true for many elements. - Putting frequently changing state on
bodyor:root. The match is cheap, but the page-wide restyle and re-checking are not. - Optimizing before measuring. A
.card:has(img)rule on 40 cards will not show up in a profile. Spend your effort on the selectors that do. - Using
>to speed up a selector that then misses wrapped content. A faster selector that no longer matches is a bug.
Exercises
Exercise
A stylesheet contains :has(> input:invalid) { border-color: crimson; }. Name two problems with its performance and rewrite it for a form built from .field wrappers.
Show answer
The subject is bare, so every element in the document is a candidate and the browser runs the argument check on all of them. The rule also does not say which elements should get the border. Anchor it to the wrapper: .field:has(> input:invalid) { border-color: crimson; }. Now only .field elements are candidates, and each checks only its direct children.
Exercise
You want h3 elements that are followed directly by a <ul> to have a smaller bottom margin. Which is cheaper, h3:has(~ ul) or h3:has(+ ul), and does the choice change which headings match?
Show answer
h3:has(+ ul) is cheaper because it examines only the next sibling. The choice changes the result: ~ also matches an h3 whose list appears later with other elements between them, while + matches only when the list comes immediately after. Use + when that is what you mean.
Exercise
A page sets body:has(.toast.visible) { overflow: hidden; }. The toast appears about once a minute. Is this a performance concern? What would change your answer?
Show answer
Probably not. The subject is a single element, and the state changes rarely, so re-checking the argument and restyling happen only a few times. It would become a concern if the state changed many times per second, for example if the toast were animated by toggling classes every frame. In that case, put the state on a smaller container or move the animation to a property that does not depend on the :has() match. Either way, confirm with a profile.