Sub topic 3
Combining Feature Detection with Responsive CSS
Assume you know CSS selectors, the cascade, source order, and @media. You should also know basic JavaScript. This chapter combines feature tests with responsive rules and shows how to test both paths.
Combining `@supports` with `@media` and `@layer
Conditional group rules can be nested. Use @media when the condition is about the viewport. Use @supports when it is about a browser capability. This example applies the enhanced layout only when both conditions are true:
@media (min-width: 40rem) {
@supports (display: grid) {
.page {
display: grid;
grid-template-columns: 16rem 1fr;
gap: 1rem;
}
}
}A cascade layer, written with @layer, controls priority between groups of rules. Put the baseline in one layer and enhancements in a later layer:
@layer base, enhancements;
@layer base {
.gallery {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
}
@layer enhancements {
@supports (display: grid) {
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(12rem, 1fr));
}
}
}The baseline remains usable when Grid is unavailable.
Running the Same Check in JavaScript
JavaScript can test the same capability with CSS.supports():
if (CSS.supports("display", "grid")) {
document.documentElement.classList.add("has-grid");
}
const canUseHas = CSS.supports("selector(:has(a))");The method returns a Boolean: true when the browser understands the declaration or selector, and false otherwise. Use this for behavior that CSS alone cannot provide.
Common Pitfalls and Debugging
- Put the fallback before the enhancement. Later declarations or stronger layers can otherwise hide the fallback.
- Parenthesize mixed operators. Write
((display: grid) and (gap: 1rem)) or (display: flex). - Test the complete condition. A browser may support a property but not the value or syntax you need.
- For selector tests, use
@supports selector(:has(img)), not a declaration test. - Inspect the rule in developer tools. If it is crossed out, the condition passed but another cascade rule won. If it is absent, inspect the condition and stylesheet loading.
> Common browser-version advice is less reliable than testing the feature itself. Capabilities can differ across engines and embedded browsers.
Testing Baseline and Enhanced Experiences
Test with the feature available and unavailable. Use developer tools to emulate older browsers when possible, or temporarily change the condition to force each branch. Confirm that the baseline still has readable content, usable controls, and a sensible layout. Then verify the enhancement at its target viewport and inspect the computed styles.
Exercise
Why can an enhancement inside both @media and @supports fail to appear?
Show answer
Either the viewport condition or the feature condition may be false, or a later or stronger cascade rule may override the enhancement.