Sub topic 9
Running the same check in JavaScript with CSS.supports()
The @supports rule lets a stylesheet decide which rules to apply. Sometimes a script needs the same decision. It might add a class, load an optional module, or pick between two ways of measuring something. CSS.supports() is the JavaScript counterpart of @supports. It runs the same parser and the same support test, and it returns a boolean.
This chapter assumes you know how @supports conditions are written, including not, and, or and selector(). It also assumes you can read basic JavaScript: functions, if statements, const, and classList.
What CSS.supports() is
CSS.supports() is a static method on the global CSS object. It asks the browser's CSS parser a yes-or-no question: "Would you accept this declaration or condition?" The answer is true or false. It does not change the page, and it does not look at the user-agent string. It is feature detection, just as @supports is.
The method has two call forms.
| Form | Arguments | Example |
|---|---|---|
| Two arguments | A property name and a value, as two strings | `CSS.supports('display', 'grid')` |
| One argument | A full condition, written as in `@supports` | `CSS.supports('(display: grid) and (gap: 1rem)')` |
The two forms give the same answer for the same test. They differ in what they can express.
The two-argument form
Pass the property name as the first string and the value as the second. You do not write a colon, parentheses or a semicolon.
console.log(CSS.supports('display', 'grid')); // true in modern browsers
console.log(CSS.supports('display', 'banana')); // false: not a valid value
console.log(CSS.supports('colour', 'red')); // false: not a property
console.log(CSS.supports('color', 'rgb(0 0 0 / 50%)')); // true where space-separated rgb() is parsedA call returns false for two different reasons: the browser does not know the property, or it knows the property but not that value. The method does not say which. This matches @supports, where the whole declaration must be valid.
The two-argument form can only test one declaration. It cannot combine tests or ask about selectors. Use it for quick checks.
The one-argument form
The one-argument form takes a string that holds a complete @supports condition. This is the part inside the parentheses after @supports, without the @supports keyword and without the braces.
const hasGridAndGap = CSS.supports('(display: grid) and (gap: 1rem)');
const canBlur = CSS.supports(
'(backdrop-filter: blur(4px)) or (-webkit-backdrop-filter: blur(4px))'
);
const canUseHas = CSS.supports('selector(:has(a))');
const noGrid = CSS.supports('not (display: grid)');Everything you learned about @supports syntax applies here without change.
- Each declaration is wrapped in its own parentheses.
- Mixing
andwithorneeds explicit parentheses around each group. If you leave them out, the condition is invalid and the call returnsfalse. selector()tests whether a selector parses.
This is what the @supports rule in your stylesheet does, evaluated at the moment you call it. The one-argument form is useful because you can copy a condition from your CSS into your script and know the two agree.
// Matches this stylesheet rule exactly:
// @supports ((display: grid) and (gap: 1rem)) or (display: flex) { ... }
const useToolbarLayout = CSS.supports(
'((display: grid) and (gap: 1rem)) or (display: flex)'
);Guarding against a missing CSS object
Browsers that are old enough to lack @supports may also lack CSS.supports(). In Internet Explorer 11, the global CSS object does not exist, so calling CSS.supports() throws a ReferenceError. If you still serve such browsers, wrap the call in a helper that never throws.
function supports(...args) {
if (typeof CSS === 'undefined' || typeof CSS.supports !== 'function') {
return false;
}
return CSS.supports(...args);
}
console.log(supports('display', 'grid'));
console.log(supports('selector(:has(a))'));The helper treats "cannot ask" the same as "not supported". That is the safe choice, because the baseline experience must work when the answer is false.
Using typeof CSS matters. A plain if (CSS) throws when CSS is undeclared, but typeof on an undeclared name returns "undefined".
Exposing results as classes
A common pattern is to run a few checks once at startup and record the results on the <html> element. Your stylesheet and your other scripts can then read them.
const checks = {
grid: ['display', 'grid'],
subgrid: ['grid-template-columns', 'subgrid'],
blur: ['(backdrop-filter: blur(4px)) or (-webkit-backdrop-filter: blur(4px))'],
has: ['selector(:has(a))'],
};
const root = document.documentElement;
for (const [name, args] of Object.entries(checks)) {
const ok = typeof CSS !== 'undefined' && CSS.supports(...args);
root.classList.add(ok ? `has-${name}` : `no-${name}`);
}After this runs, the <html> element carries classes such as has-grid and no-subgrid. A rule like .has-blur .panel { ... } can now use the result.
The script spreads each array into CSS.supports(). One array has two items, so it makes a two-argument call. The others have one item, so they make one-argument calls.
When to use CSS or JavaScript
Prefer @supports in the stylesheet whenever the decision is only about styling. It runs before first paint, needs no script, and keeps the logic next to the rules it affects. A class set by JavaScript can arrive after the first render. That can make the page flash from the baseline to the enhanced layout.
Use CSS.supports() when the decision changes behaviour that CSS cannot control:
- Loading a script, polyfill or stylesheet only when the browser needs it.
- Choosing between two measurement strategies in code.
- Reporting which features a user's browser has, for example in a support tool.
- Skipping an animation library when a native CSS feature already does the job.
async function setUpScrollEffects() {
if (CSS.supports('animation-timeline', 'scroll()')) {
// The browser animates on scroll without JavaScript. Nothing to do.
return;
}
// Placeholder module name: replace it with your own fallback implementation.
const { startScrollFallback } = await import('./scroll-fallback.js');
startScrollFallback();
}
setUpScrollEffects();In this example, the path ./scroll-fallback.js is a stand-in for a module you would write yourself. The point is the shape: native support means no extra code is loaded.
A diagnostic helper
CSS.supports() is also useful for debugging. You can paste a condition into the browser console and see whether the browser accepts it. This is faster than editing a stylesheet and reloading.
function report(conditions) {
const rows = conditions.map((condition) => ({
condition,
supported: CSS.supports(condition),
}));
console.table(rows);
}
report([
'(display: grid)',
'(display: subgrid)',
'(gap: 1rem)',
'selector(:has(img))',
'(display: grid) and (gap: 1rem) or (display: flex)',
]);The last condition mixes and and or without grouping parentheses. The table shows false for it in every browser. This is the same mistake that stops an @supports block from applying. Fix it by adding explicit parentheses:
console.log(CSS.supports('((display: grid) and (gap: 1rem)) or (display: flex)'));Edge cases and gotchas
- Parentheses in the one-argument form. The one-argument form is a condition, so a single declaration should be in parentheses:
'(display: grid)'. Current browsers also accept'display: grid'and retry it with parentheses added, but older engines may not. Write the parentheses to stay safe. - No semicolons or
!important. The two-argument value must be a plain value.CSS.supports('color', 'red !important')returnsfalse, and so does a trailing semicolon in the value. - Custom properties always pass.
CSS.supports('--brand', 'anything')istrue, because custom properties accept almost any value. It tells you nothing useful about whether your intended value will work when used. - It tests parsing, not rendering. A
trueresult means the browser understands the syntax. It does not prove the feature works well, is hardware accelerated, or is free of bugs. A property can parse in a browser whose implementation is still incomplete. - Prefixes are separate tests.
backdrop-filterand-webkit-backdrop-filterare different properties. Test both, joined withor, as the example above does. - Values change with the viewport or context.
CSS.supports()does not look at the media query. For viewport conditions, usewindow.matchMedia()instead. You can combine the two in a script, just as you nest@supportsinside@mediain CSS. - The answer does not change while the page is open. The browser's capabilities are fixed for a session, so you can compute a result once and cache it.
Keeping the stylesheet and the script in agreement
If a rule in CSS says @supports (display: grid) and your script checks CSS.supports('display', 'flex'), the two will disagree on some browsers. This kind of drift is easy to introduce and hard to notice.
There are two simple ways to avoid it.
- Put the check in only one place. Run it in JavaScript, set a class, and let the stylesheet use the class. The downside is the possible flash described earlier.
- Put the check in CSS and read the result from JavaScript. Use
@supportsto set a custom property, and read it back withgetComputedStyle().
:root {
--has-grid: 0;
}
@supports (display: grid) {
:root {
--has-grid: 1;
}
}const hasGrid =
getComputedStyle(document.documentElement).getPropertyValue('--has-grid').trim() === '1';
console.log(hasGrid);The CSS holds the only copy of the condition. The script reads its result. This works because getPropertyValue() returns the custom property as a string, and the whitespace around it must be trimmed.
Summary of the call forms
| Goal | Call | Result |
|---|---|---|
| Test one property and value | `CSS.supports('gap', '1rem')` | `true` or `false` |
| Test a full condition | `CSS.supports('(display: grid) and (gap: 1rem)')` | `true` or `false` |
| Test a selector | `CSS.supports('selector(:has(a))')` | `true` or `false` |
| Test that something is missing | `CSS.supports('not (display: grid)')` | `true` or `false` |
| Guard for very old browsers | `typeof CSS !== 'undefined' && CSS.supports(...)` | `true` or `false` |
Exercise
A page uses .panel with a translucent blur only where the browser supports backdrop-filter, either unprefixed or with the -webkit- prefix. Write a JavaScript function addBlurClass() that adds the class has-blur to the <html> element when the browser supports it, and does nothing when it does not or when CSS is unavailable.
Show answer
function addBlurClass() { if (typeof CSS === 'undefined' || typeof CSS.supports !== 'function') { return; } const ok = CSS.supports( '(backdrop-filter: blur(8px)) or (-webkit-backdrop-filter: blur(8px))' ); if (ok) { document.documentElement.classList.add('has-blur'); } } addBlurClass();
Exercise
Explain why CSS.supports('(display: grid) and (gap: 1rem) or (display: flex)') returns false in every browser, and rewrite the call so that it is valid.
Show answer
Mixing and with or at the same level without parentheses makes the condition invalid, so the parser rejects it and the method returns false. Group each part explicitly: CSS.supports('((display: grid) and (gap: 1rem)) or (display: flex)').
Exercise
Give two situations where you should use @supports in the stylesheet instead of CSS.supports(), and one situation where CSS.supports() is the better choice.
Show answer
Use @supports when the decision only changes styles, because it applies before first paint and needs no script. Use it too when you want the condition to sit beside the rules it controls. Use CSS.supports() when the result changes behaviour that CSS cannot control, such as loading a polyfill module only when the browser lacks the native feature.