Sub topic 6
Testing selector support with selector()
This chapter assumes you can already write a basic @supports (property: value) rule and that you understand how source order and the cascade resolve conflicts. You should also be comfortable with @media. The last section uses a few lines of JavaScript, so you need only basic JavaScript.
Why properties are not enough
The property test @supports (display: grid) asks whether the browser understands a declaration. Many modern CSS features are selectors, and a declaration test can't ask about them. :has(), :focus-visible, :user-invalid and ::backdrop all have a syntax that a browser either parses or doesn't.
An unsupported selector causes a quiet failure. When a browser can't parse a selector, it discards the whole rule that contains it. Nothing is logged to the page, and the element simply stays unstyled. Because an unsupported selector invalidates the whole rule, the failure can also reach further than you intended.
/* Unsafe: one unknown selector invalidates the whole list */
.card:hover,
.card:has(img) {
border-color: rebeccapurple;
}In a browser without :has(), this rule is dropped entirely. The :hover half is lost along with the :has() half, even though :hover is supported everywhere. The usual fix is to split the selectors into separate rules. The selector() function goes further. It lets you state your intent: apply this rule only if the browser can parse this selector.
The syntax
Inside an @supports condition, selector() takes one selector as its argument. The condition is true if the browser can parse that selector.
.card {
border: 1px solid #ccc;
}
@supports selector(:has(img)) {
.card:has(img) {
border-color: rebeccapurple;
}
}Here is how it works:
- The
.cardrule is the baseline. Every browser applies it. - The
@supports selector(:has(img))block is the enhancement. A browser applies it only if it can parse:has(img). - Inside the block, you write the real rule with the real selector.
Notice that the selector in the condition and the selector in the rule can differ. The condition tests that the browser understands the syntax. It doesn't need to match your actual markup. Testing :has(img) is a reasonable proxy for "this browser supports :has()".
Two details about the syntax are easy to get wrong:
- There is no
@supports (selector(...))form that needs extra parentheses. You writeselector(...)directly after@supports. If you combine it with other conditions,and,orandnotwork as in the previous chapter. - The argument is a single complex selector, so a comma-separated list is not valid. Test one selector per
selector()call.
What happens in a browser that doesn't know selector()
selector() itself arrived in @supports before most of the selectors people use it to test. Chrome 83, Firefox 69 and Safari 14.1 support it. A browser that doesn't recognize the selector() function treats the unknown function as a condition it can't evaluate, and the condition counts as false. The block is skipped. Browsers that don't support @supports at all, such as Internet Explorer 11, also skip the block, because they ignore the whole unknown at-rule.
In both cases the result is the one you want. The old browser gets your baseline and nothing else. You don't need to add a second test for selector() support.
How the browser evaluates it
The browser makes the check when it parses the stylesheet. It doesn't look at your document and it doesn't test any elements.
The check tests parsing, not behavior. A browser can parse a selector and still match it badly or slowly, and selector() can't tell you that. It also can't tell you whether your page contains matching elements. It answers one question: is this syntax valid here?
Common selectors to test
| Feature | Condition | Typical use |
|---|---|---|
| Parent selector | `selector(:has(img))` | Style a container based on its children |
| Keyboard focus | `selector(:focus-visible)` | Show focus rings only for keyboard use |
| Logical matching | `selector(:is(h1, h2))` | Shorter selector lists |
| Native dialog backdrop | `selector(::backdrop)` | Style the area behind a dialog |
| Vendor pseudo-element | `selector(::-webkit-scrollbar)` | Style scrollbars where the engine allows it |
Vendor-prefixed selectors work in selector() like any other. This makes it a clean way to scope engine-specific styling instead of letting those rules sit in your general stylesheet.
A worked example: :focus-visible
Older browsers don't support :focus-visible. A common mistake is to remove the focus outline for all mouse clicks with :focus-visible and nothing else, which leaves older browsers with no outline at all. The safe approach starts from a baseline that always works and refines it only where supported.
/* Baseline: every browser shows an outline on focus */
button:focus {
outline: 3px solid #1a73e8;
outline-offset: 2px;
}
/* Enhancement: remove the outline for mouse clicks,
but keep it for keyboard focus */
@supports selector(:focus-visible) {
button:focus:not(:focus-visible) {
outline: none;
}
}Look at what each browser does:
- A browser with
:focus-visibleshows the outline for keyboard users and hides it after a mouse click. - A browser without
:focus-visibleskips the block and keeps showing the outline in every case. Mouse users see a slightly noisier page, but keyboard users are never left without a focus indicator.
Without the @supports wrapper, the second rule would be invalid in an old browser and dropped, which gives the same result here. The wrapper makes the intent explicit, and it protects you when a rule mixes a supported part and an unsupported part in a single selector.
Using not for a targeted workaround
You can invert the test to write a fix only for browsers that lack a selector:
@supports not selector(:focus-visible) {
button:focus {
box-shadow: 0 0 0 3px #1a73e8;
}
}This pattern is useful for a patch aimed at a known gap. As with property tests, a baseline plus an enhancement is usually easier to read than a not block. There is also a limit on what not can cover. A browser that doesn't know selector() evaluates this condition as false, so a @supports not selector(...) block runs only in browsers that know selector() and reject the selector. It never runs in a browser too old to understand selector() at all. If you need the workaround for those browsers too, put it in the baseline and let the enhancement override it.
Combining selector() with other conditions
selector() works with the operators from the previous chapter. This rule needs both :has() and a grid layout:
@supports selector(:has(img)) and (display: grid) {
.card:has(img) {
display: grid;
grid-template-columns: 8rem 1fr;
gap: 1rem;
}
}Parentheses rules still apply. You can chain several and operators, or several or operators, without extra parentheses. If you mix and with or, you must add parentheses around each group. For example:
@supports (selector(:has(img)) and (display: grid)) or (display: flex) {
.card {
display: flex;
}
}Without the outer grouping the condition would be invalid, and the block would never apply.
Pitfalls specific to selector()
Forgiving selector lists accept almost anything
:is() and :where() use forgiving parsing. If one entry in their list is invalid, the browser ignores that entry and keeps the rest. This means a test such as selector(:is(:not-a-real-thing)) can return true in a browser that supports :is(), because the invalid part is forgiven. Test the selector you actually need, not a wrapper around it.
/* Misleading: tests :is(), not :has() */
@supports selector(:is(:has(img))) { /* ... */ }
/* Clear: tests :has() directly */
@supports selector(:has(img)) { /* ... */ }Supported syntax is not the same as full behavior
A browser may parse a selector but support only part of what it can express. Early implementations of some selectors had limits on where they could be used. Test the exact form you plan to use, and then check the result in the browsers you care about. The @supports check alone doesn't verify behavior.
The condition is evaluated once
The browser decides at parse time. If the user changes something later, such as resizing the window or toggling a setting, the @supports result does not change. Use @media for conditions that depend on the environment, and use @supports only for what the browser itself can do.
Don't test the selector you are about to use
A mistake that appears in many stylesheets is checking something unrelated to the rule inside. If the block styles .card:has(img), test selector(:has(img)), not selector(.card). The condition should name the risky part of the selector, which is the new syntax.
Checking in JavaScript
CSS.supports() accepts the same selector() syntax as a string. This lets a script make the same decision as the stylesheet. That is useful when a script needs to choose between two approaches.
const canUseHas = CSS.supports('selector(:has(a))');
if (canUseHas) {
document.documentElement.classList.add('has-parent-selector');
} else {
// Fall back to a script that marks cards that contain images
document.querySelectorAll('.card').forEach((card) => {
if (card.querySelector('img')) {
card.classList.add('card--with-image');
}
});
}In the fallback branch, the script adds a class that does the job of :has(). The stylesheet can then target .card--with-image in a rule that every browser understands. Keep the two paths in step: the class-based rule and the :has() rule should produce the same look, or users will see different pages depending on their browser.
You can also check a selector before using it with querySelector(). Calling querySelector() with an unsupported selector throws a SyntaxError, so a pre-check with CSS.supports() avoids a try/catch.
const selectorText = ':has(> img)';
if (CSS.supports(`selector(${selectorText})`)) {
const cards = document.querySelectorAll(`.card${selectorText}`);
console.log(`Found ${cards.length} cards with a direct image child`);
}Debugging a selector() block that doesn't apply
When a selector() block does nothing, work through these checks in order:
- Open the browser's developer tools and look at the rule inside the
@supportsblock. If the tools show it greyed out or missing, the condition evaluated to false. - Run
CSS.supports('selector(...)')in the console with the same text. If it returnsfalse, the browser doesn't parse that selector, or you made a typo. - Check the parentheses.
selector(:has(img)with a missing closing bracket makes the condition invalid. - Check for a comma. A selector list inside
selector()is invalid. - Check specificity and source order. If the condition is true but the style still doesn't show, the rule inside may lose to a more specific baseline rule.
The last check matters because @supports doesn't add any specificity. A rule inside the block has the same weight as the same rule outside it. If the baseline has higher specificity, the enhancement loses. Place the @supports block after the baseline and give both the same specificity.
Summary of the working model
- A selector the browser can't parse invalidates the whole rule it appears in.
@supports selector(...)tests one selector's syntax at parse time.- Browsers that don't know
selector()skip the block, which gives them the baseline. - Test the risky part of the selector, and don't rely on forgiving wrappers such as
:is(). CSS.supports('selector(...)')makes the same test in JavaScript.
Exercise
A stylesheet contains .nav a:hover, .nav a:has(svg) { color: teal; }. Users on a browser without :has() report that the hover color no longer works. Explain why, then rewrite the CSS so hover works everywhere and the :has(svg) styling applies only where supported.
Show answer
A browser that can't parse :has() treats the whole selector list as invalid and drops the entire rule, including the :hover part. Split the rules and wrap the unsupported one: .nav a:hover { color: teal; } followed by @supports selector(:has(svg)) { .nav a:has(svg) { color: teal; } }. Hover now works in every browser, and the :has(svg) rule applies only where the browser parses :has().
Exercise
Write a condition that is true only when the browser supports both the :has(img) selector and display: grid. Then write a JavaScript line that returns the result of the same check.
Show answer
In CSS: @supports selector(:has(img)) and (display: grid) { ... }. In JavaScript: CSS.supports('selector(:has(img)) and (display: grid)'). Both use and with no mixed operators, so no extra parentheses are needed.