Sub topic 2
Detect Features, Not Browsers
This chapter assumes you can write basic CSS (selectors, properties, values) and that you know how source order and the cascade resolve conflicting declarations. You should also know what an at-rule such as @media looks like. The JavaScript examples need only basic syntax.
By the end you will be able to explain why checking for a feature is more reliable than checking for a browser name. You will also know where each check has limits, and when a browser check is still justified.
The question behind every enhancement
When you want to use a newer CSS feature, you are really asking one question: can this browser do the thing I am about to ask of it? There are two ways to answer.
- Ask who the browser is, then look up what you believe that browser can do. This is browser sniffing, usually done by reading the user-agent string. The user-agent string is a line of text that the browser sends with every request and exposes in JavaScript as
navigator.userAgent. - Ask the browser directly whether it understands the feature. This is feature detection.
The first approach relies on a lookup table in your head, or in your code. The second relies on the browser's own parser, which is the part that decides what it will do with your CSS. Feature detection is almost always the better choice, and the rest of this chapter explains why.
Why browser sniffing breaks
A sniffing check looks like this:
const ua = navigator.userAgent;
const match = ua.match(/Version\/(\d+)[\d.]*.*Safari/);
const safariVersion = match ? Number(match[1]) : null;
// Assumption: Safari older than 16 cannot do what we want.
const useFallbackLayout = safariVersion !== null && safariVersion < 16;
if (useFallbackLayout) {
document.documentElement.classList.add('legacy-layout');
}This code runs without errors, but it makes several assumptions that tend to fail.
The string is not reliable
User-agent strings are historically messy. Nearly every browser claims to be "Mozilla" and many include the word "Safari" for compatibility. A regular expression that was correct last year can match the wrong browser this year.
Browsers also change the string on purpose. Several vendors have reduced the user-agent string, which means they freeze parts of it, such as the minor version numbers, to limit fingerprinting. Users and extensions can also override it. Your check would then read a value the browser chose to show, which may not match what the browser can do.
The browser name does not identify the engine
A rendering engine is the part of a browser that parses and draws CSS. Different browsers can share an engine, and one browser can use different engines on different platforms. On iOS, for example, third-party browsers have historically had to use the system's WebKit engine. A check for "Chrome" there tells you very little about CSS support.
The version number does not identify the feature set
Even when the name and version are correct, they are only a proxy. Features can be:
- behind a flag that is off by default, or on in a preview build,
- turned off by an enterprise policy,
- partly implemented, so that some values work and others do not,
- backported to a long-term-support release without a version bump you would expect.
A lookup table such as "grid works from version X" is a snapshot. You have to maintain it, and nothing warns you when it goes stale.
Unknown browsers get the wrong answer
A sniffing list contains the browsers its author knew about. A new or niche browser falls through to a default. That default is usually "assume modern", which breaks old engines, or "assume legacy", which denies a good experience to a capable browser.
How feature detection works
With feature detection you let the browser's parser decide. In CSS, the browser throws away any declaration it cannot parse, and the @supports at-rule lets you test for this directly. In JavaScript, CSS.supports() runs the same test.
if (CSS.supports('display', 'grid')) {
document.documentElement.classList.add('has-grid');
}.gallery {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.gallery > * {
flex: 1 1 12rem;
}
@supports (display: grid) {
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(12rem, 1fr));
}
}The CSS is a preview. The syntax of @supports gets its own chapter later. The point for now is what the code does not contain: a browser name, a version number, or a list. The question is "do you understand display: grid?", asked of the browser that is about to run the code. A browser I have never heard of gets the correct answer, and so does one that has the feature behind a flag, or one that was released after I wrote the stylesheet.
The flexbox rules outside the @supports block are the baseline. Every browser gets them. The grid rules are an enhancement that only capable browsers receive. This is the progressive enhancement pattern from the previous chapter, and feature detection is the mechanism that makes it safe.
Comparing the two approaches
| Concern | Browser sniffing | Feature detection |
|---|---|---|
| What it checks | The browser's claimed identity | Whether the browser parses the feature |
| Unknown or new browsers | Fall through to a default guess | Get the right answer automatically |
| Flags and policies | Invisible to the check | Reflected in the result |
| Maintenance | Update the list as browsers change | Little or none |
| Spoofing or string reduction | Breaks the check | No effect |
| Failure when wrong | Wrong layout for a whole browser | Usually limited to one feature |
What feature detection does not tell you
Feature detection is better than sniffing, but it is not magic. Knowing its limits will save you debugging time later.
It tests parsing, not correct rendering
@supports (display: grid) is true when the browser accepts the declaration. It does not promise that the implementation is free of bugs. If an engine parses a property but renders it wrongly, the check passes and the bug appears anyway.
A property test cannot see context
Some features were released in stages. The gap property is a well-known example. It first worked in grid layouts, and support in flexbox came later. A test for gap: 1rem only asks whether the property is known. It does not ask in which layout mode.
.toolbar {
display: flex;
gap: 0.5rem;
}
@supports (gap: 1rem) {
/* This passes in a browser that has grid gap but not flex gap. */
}When a feature is split like this, test something that only exists in the later stage, or accept the older behavior as part of your baseline. A later chapter on common pitfalls returns to this problem.
The value you test must match the value you use
Support can depend on the value. If you test (display: grid) but then use grid-template-columns: subgrid, the test does not cover the second part. Write the condition to include the specific feature your rule depends on.
@supports (display: grid) and (grid-template-columns: subgrid) {
.card-list {
display: grid;
grid-template-columns: subgrid;
}
}Some features cannot be tested from CSS
Detection works well for syntax: properties, values, and selectors. It does not cover behavior such as performance on slow hardware, or whether a feature interacts correctly with an assistive technology. For those you need testing on real browsers and devices, a topic covered in the final chapter.
When sniffing is still defensible
Sniffing is a last resort, and a narrow one. It can be justified when all of these are true:
- A specific browser has a confirmed bug in a feature it claims to support.
- No feature test can distinguish the buggy browser from the working ones.
- The workaround is harmless for everyone else.
In that case, isolate the check in one place, write a comment that links to the bug report, and name the version range. Plan to delete it when the bug is fixed. A sniffing check should be a small, documented exception, not the way your code decides what to do.
// Workaround for a hypothetical engine bug: see issue tracker entry.
// Remove when the fixed release is the minimum supported version.
const hasKnownBug = /ExampleEngine\/(\d+)/.test(navigator.userAgent) &&
Number(/ExampleEngine\/(\d+)/.exec(navigator.userAgent)[1]) < 120;
if (hasKnownBug) {
document.documentElement.classList.add('workaround-example');
}A decision rule you can reuse
When you are about to write a conditional, ask these questions in order.
- Does the cascade already handle it? If an unsupported declaration is simply ignored, write the baseline first and the newer declaration after it. No condition is needed. The next chapter covers this.
- Is the feature a property, a value, or a selector? Use
@supportsin CSS, orCSS.supports()in JavaScript. - Is the problem a bug in a feature the browser claims to support? Only then consider a narrow, documented browser check.
Where this fits in the plan
Detection is the second step of progressive enhancement. First you write a baseline that works everywhere. Then you detect features and layer enhancements on top. The next chapter looks at how the cascade gives you fallbacks without any condition at all, and the chapter after that writes @supports rules in full.
Exercise
A teammate proposes this check: "If the user-agent string contains 'Firefox', add the class no-backdrop so we skip backdrop-filter." Give two reasons this is fragile, and write the feature-detection alternative in JavaScript that adds the class has-backdrop only when the browser supports backdrop-filter (or its -webkit- prefixed form).
Show answer
The check is fragile because (1) the browser name does not tell you the feature set: the feature may be supported or unsupported depending on the version, flags, or platform, and the code will be wrong the moment that changes, and (2) the user-agent string can be reduced, changed by the user, or shared across browsers, so the match may be wrong or missing. Feature-detection alternative: if (CSS.supports('(backdrop-filter: blur(4px)) or (-webkit-backdrop-filter: blur(4px))')) { document.documentElement.classList.add('has-backdrop'); }. This asks the browser directly and works for browsers the teammate has never heard of.
Exercise
A stylesheet uses @supports (gap: 1rem) to switch a flexbox toolbar to a layout that depends on flex gap. In one older browser, the layout is broken. Explain the likely cause in terms of what the test measures.
Show answer
The test only checks that the browser parses the gap property, not that it supports gap in flex containers. The older browser may support gap for grid only, so the condition is true while flex gap has no effect. Fix it by making the baseline work without flex gap (for example with margins), or by testing a feature that appears only in browsers that support flex gap.