CSS Media Queries
css media queries media queries apply styles based on the device — viewport width, orientation, color scheme, motion preferences, hover
Introduction
Media queries apply styles based on the device — viewport width, orientation, color scheme, motion preferences, hover capability. They're the bedrock of responsive design.
Business problem
Business pressure: Product teams ship media queries across dozens of surfaces — marketing, checkout, admin dashboards — and expect pixel parity without layout regressions that hurt conversion or trigger accessibility complaints.
- Conversion: Airbnb-style polish depends on consistent media queries tokens; one-off CSS breaks trust on high-value flows.
- Velocity: Without a shared media queries contract, every squad reinvents spacing, states, and responsive behavior.
- Risk: Visual debt compounds — refactors cost more than getting media queries right in the design system.
Why this feature exists
Platform history: CSS added media queries so authors could express layout and visual intent declaratively instead of table hacks, image slices, or JavaScript layout engines.
- Problem solved: Separates presentation from document structure while staying cacheable and themeable.
- Rejected alternative: Inline styles and per-page one-offs — unmaintainable at enterprise scale.
- Today: Design tokens and component APIs expose media queries as the single source of truth.
Browser rendering perspective
Rendering impact: media queries participates in style recalculation and may trigger layout, paint, or compositor work depending on which properties change.
- Chrome (Blink): Blink LayoutNG resolves media queries during style → layout → paint → composite.
- Firefox (Gecko): Servo-based stylo computes values; WebRender composites promoted layers.
- Safari (WebKit): Style resolver + GPU layer rules — test media queries on real iOS devices, not just desktop Safari.
Internal browser workflow
Workflow: Selector match → cascade → computed values → layout tree → paint layers → composite. Changes to media queries may invalidate earlier stages.
- DevTools: Elements panel → Computed → trace which rule won the cascade for media queries.
- Layout: Toggle "Layout" badge in Rendering tab when debugging media queries shifts.
- Layers: Check whether media queries promoted a compositor layer unnecessarily.
Syntax
Wrap rules in @media (condition) { ... }:
@media (min-width: 720px) {.grid { grid-template-columns: 1fr 1fr; }}@media (prefers-color-scheme: dark) {body { background: #0f172a; color: white; }}@media (prefers-reduced-motion: reduce) {* { animation-duration: .01ms !important; }}
Real-world use
A typical site has 2–3 breakpoints (e.g. 640, 1024, 1280). Mobile-first — write base styles, then add @media (min-width) — keeps stylesheets small.
Real production example
Production: Airbnb codifies media queries in design tokens, Stylelint rules, and visual-regression CI so PRs cannot ship ad-hoc overrides.
- Pattern: Token pipeline emits CSS custom properties consumed by components.
- CI: Percy/Chromatic snapshots catch media queries drift across themes.
- Observability: RUM correlates CLS/LCP with media queries changes on hero surfaces.
Enterprise use case
Enterprise: Polaris, Carbon, and Atlassian Design System document media queries in component APIs — not in page-level CSS.
- Multi-brand: White-label tenants override tokens, not raw media queries rules.
- Dark mode: Scoped variable overrides propagate media queries consistently.
- Governance: Architecture review for new media queries patterns outside the system.
Accessibility considerations
A11y: media queries must not remove focus visibility, break zoom, or convey state by color alone (WCAG 2.2).
- Focus: :focus-visible outlines survive media queries resets — never
outline: nonewithout replacement. - Motion: Honor
prefers-reduced-motionwhen media queries includes animation. - Contrast: Visual effects from media queries cannot be the only error indicator.
Performance considerations
Performance: media queries can trigger reflow, expensive paint, or layer explosion — profile with DevTools Performance panel.
- CLS: Reserve space before media queries loads or animates into place.
- Paint: Prefer transform/opacity over properties that repaint large regions.
- Selectors: Deep selectors targeting media queries slow style recalc on large DOMs.
SEO considerations
SEO: media queries affects LCP, CLS, and mobile usability — ranking signals tied to Core Web Vitals.
- LCP: Hero media queries must not delay largest content paint.
- Mobile: Google mobile-first indexing sees the same media queries as users on phones.
- Legibility: Text effects from media queries must stay readable without zoom.
Scalability considerations
Scale: media queries choices compound across micro-frontends, white-label tenants, and dark-mode variants.
- Tokens: Centralize media queries values — avoid 47 slightly different radii.
- Micro-frontends: Shadow DOM and CSS modules isolate media queries per team.
- Migration: Document deprecation path when media queries API changes.
Common production issues
Production failures: Specificity wars, z-index stacks, and responsive rules that work in Chrome but break Safari — common media queries incident patterns.
- Regression: Global reset broke media queries on legacy iframe embeds.
- Theme leak: Dark-mode media queries overrode light admin shell.
- Print: media queries hid critical content in PDF exports.
Debugging guide
Debug: Chrome DevTools → Elements (computed styles), Layout panel, Rendering layers, Coverage for unused CSS affecting media queries.
- Cascade: Find which stylesheet wins for media queries.
- Forced state: :hov / :cls toggles in DevTools for hover/focus media queries.
- Diff: Compare computed media queries values across browsers in BrowserStack.
/* DevTools console — inspect computed media queries */const el = document.querySelector('.target');console.log(getComputedStyle(el).getPropertyValue('/* property */'));
Best practices
- Mobile-first: design narrow first, then add min-width queries.
- Use rem-based breakpoints for accessibility.
- Combine queries:
@media (min-width: 720px) and (orientation: landscape).
Anti-patterns
- Magic numbers: Hard-coded media queries values instead of design tokens.
- !important escalation: Fighting specificity instead of fixing cascade order.
- Global overrides: Page CSS rewriting component media queries from outside.
Trade-offs
- Benefit: Declarative media queries keeps UI consistent and testable.
- Cost: Learning curve and cross-browser edge cases for advanced media queries.
- Trade-off: Pure CSS media queries vs JS libraries — simpler CSS wins until a11y/complexity demands JS.
Architecture review questions
- Are media queries values sourced from design tokens, not one-off literals?
- Does media queries pass axe and keyboard navigation on interactive targets?
- What is the CLS impact if media queries assets load late?
- How does media queries behave at 200% zoom and in high-contrast mode?
- Is there a Safari/iOS verification checklist for media queries?
- Can we remove unused media queries rules flagged by Coverage?
Interview questions
Explain media queries to a backend engineer — why does it belong in CSS, not JS?(Intermediate)
media queries is declarative presentation: browsers optimize layout/paint pipelines for CSS, stylesheets cache independently of JS bundles, and theming stays runtime-swappable via custom properties. JS layout belongs when you need measurement loops CSS cannot express.
Follow-up: When would you reach for JS instead?
How does media queries affect Core Web Vitals?(Advanced)
Depends on property: layout-affecting media queries can hurt CLS if space isn't reserved; paint-heavy effects hurt LCP on hero elements; animating non-composited properties hurts INP. Profile and prefer transform/opacity.
Follow-up: Which DevTools panels do you use?
Design system team wants to standardize media queries — what do you document?(Advanced)
Token names, allowed values, component API props, anti-patterns, browser support matrix, a11y requirements, and visual-regression baselines. Include migration notes from legacy one-offs.
Follow-up: How do you enforce in CI?
Hands-on exercise
Exercise: Implement media queries in a component that passes axe, Lighthouse performance ≥ 90, and a visual-regression snapshot on light/dark themes.
- Deliverable: Component + token definitions + Try It demo.
- Verify: Safari iOS + Firefox + Chrome computed style parity.
- Stretch: ADR documenting media queries trade-offs vs alternatives.
Staff engineer notes
- media queries is an engineering decision — measure it with Web Vitals and a11y audits, not screenshots alone.
- Tokenize media queries early; retrofitting 200 components costs quarters.
- When media queries breaks in Safari, check prefixes, stacking contexts, and subpixel rounding — not just syntax.
Common pitfalls
- Too many breakpoints = exponential bug surface.
- Hardcoded px breakpoints don't scale with text size.
Try it yourself
Edit the CSS panel — the preview updates live. Use DevTools Performance and Accessibility panels to validate.
Try it yourself
Summary
Media Queries separates tutorial demos from production engineering: tokenized values, cross-browser verification, Web Vitals-safe animation, and WCAG-compliant states — the patterns Airbnb and peers enforce via design systems and CI.
Key takeaways
- Mobile-first scales better.
- @media supports more than width (color scheme, motion, hover).
- Fewer breakpoints = simpler CSS.