CSS Media Queries
A media query is a CSS rule that applies styles only when a
specific condition about the user's device or environment is true. They are the foundation of responsive
design — the same HTML file can render completely differently on a phone, a tablet, a widescreen monitor,
when printed, or when the user has requested dark mode. This chapter covers the full @media syntax, every major media feature, mobile-first strategy, standard
breakpoints, logical operators, and the modern range query syntax.
@media syntax and structure
and, or, not@media Syntax
A media query has two optional parts — a media type and one or more media features in parentheses. The styles inside apply only when the condition is true:
/* Feature only — most common (implies screen + all) */
@media (min-width: 768px) { }
/* Media type only */
@media screen { }
@media print { }
@media all { } /* default — same as no type */
/* Type + feature */
@media screen and (min-width: 768px) { }
@media print and (color) { }
/* In HTML — stylesheet for specific media */
<link rel="stylesheet" media="print" href="print.css">
<link rel="stylesheet" media="(min-width:768px)" href="wide.css">
/* Nesting inside @media (CSS nesting, modern browsers) */
@media (width >= 768px) {
.card {
grid-template-columns: repeat(2, 1fr);
}
}
Media Features
Media features describe specific characteristics of the device or browser environment.
Most range features support min-, max-, and exact prefixes:
/* Width — most common */
@media (min-width: 768px) { } /* ≥ 768px (tablet up) */
@media (max-width: 767px) { } /* ≤ 767px (mobile only) */
@media (width: 768px) { } /* exactly 768px */
/* Orientation */
@media (orientation: portrait) { } /* height > width */
@media (orientation: landscape) { } /* width > height */
/* Dark mode */
@media (prefers-color-scheme: dark) { :root { --bg: #0f172a; } }
@media (prefers-color-scheme: light) { :root { --bg: #fff; } }
/* Accessibility — reduced motion */
@media (prefers-reduced-motion: reduce) {
* { animation-duration: .01ms !important; transition-duration: .01ms !important; }
}
/* Touch vs mouse */
@media (hover: hover) and (pointer: fine) {
.btn:hover { background: #264de4; } /* only on devices with mouse */
}
@media (pointer: coarse) {
.btn { min-height: 44px; } /* larger tap targets on touch */
}
/* High-DPI (Retina) screens */
@media (min-resolution: 2dppx) {
.logo { background-image: url("logo@2x.png"); }
}
/* Print */
@media print {
nav, aside, .ads { display: none; }
a[href]::after { content: " (" attr(href) ")"; }
}
Mobile-First vs Desktop-First
The order you write media queries determines which approach you're using.
Mobile-first (recommended) starts with mobile styles as the base and adds complexity with
min-width. Desktop-first starts wide and strips back
with max-width:
/* Base: mobile */
.grid {
display: grid;
grid-template-columns: 1fr;
}
/* Add complexity up */
@media (min-width: 640px) {
.grid {
grid-template-columns: 1fr 1fr;
}
}
@media (min-width: 1024px) {
.grid {
grid-template-columns: repeat(3,1fr);
}
}
✓ Mobile gets smallest CSS download · min-width queries layer complexity upward
/* Base: wide desktop */
.grid {
display: grid;
grid-template-columns: repeat(3,1fr);
}
/* Strip back down */
@media (max-width: 1023px) {
.grid {
grid-template-columns: 1fr 1fr;
}
}
@media (max-width: 639px) {
.grid {
grid-template-columns: 1fr;
}
}
Mobile must download and parse all the desktop overrides too
Standard Breakpoints
There are no universally "correct" breakpoints — design should drive breakpoints, not devices. These are the most widely used values (inspired by Tailwind CSS):
sm
md
lg
xl
2xl
/* Mobile-first breakpoints */
/* xs: 0–639px — base (no query needed) */
@media (min-width: 640px) { } /* sm — large phones, landscape */
@media (min-width: 768px) { } /* md — tablets */
@media (min-width: 1024px) { } /* lg — small laptops */
@media (min-width: 1280px) { } /* xl — desktops */
@media (min-width: 1536px) { } /* 2xl — wide screens */
/* Use CSS custom properties for reusable breakpoints */
:root {
--bp-sm: 640px;
--bp-md: 768px;
--bp-lg: 1024px;
}
/* Note: custom properties can't be used inside @media conditions */
@media (min-width: var(--bp-md)) { } /* ✗ does NOT work */
/* Design-driven breakpoints: add where layout breaks */
@media (min-width: 52em) { } /* em-based: more accessible, scales with font-size */
@media (min-width: 800px) { } /* px-based: predictable, not affected by font settings */
Logical Operators — and, or, not
Media queries support three logical operators to combine or negate conditions:
@media screen and (min-width: 768px) — screen AND at least 768px wide.
,) or the keyword or works. @media (max-width: 600px), (orientation: portrait) — narrow OR portrait.
@media not print — everything except print. not requires a media type or must wrap a condition./* and — all conditions must match */
@media screen and (min-width: 768px) { }
@media (min-width: 768px) and (max-width: 1024px) { } /* range */
@media (hover: hover) and (pointer: fine){ } /* mouse device */
/* or / comma — any condition matches */
@media (max-width: 600px), (orientation: portrait) { }
@media screen, print { } /* screen OR print */
/* Modern 'or' keyword (Level 4) */
@media (width <= 600px) or (orientation: portrait) { }
/* not — inverts the entire query */
@media not print { } /* all except print */
@media not (prefers-color-scheme: dark) { } /* not in dark mode */
@media not screen and (max-width: 640px){ } /* not (screen AND ≤640px) */
/* Combining all three */
@media (min-width: 768px) and (max-width: 1280px) and (orientation: landscape) { }
Modern Range Syntax (Level 4)
CSS Media Queries Level 4 introduces a cleaner range syntax using comparison operators
(<, >, <=, >=) instead of min- and max- prefixes. All modern
browsers support it:
/* >= replaces min- */
@media (width >= 768px) { } /* same as min-width: 768px */
@media (width > 768px) { } /* strictly greater than */
/* <= replaces max- */
@media (width <= 1280px) { } /* same as max-width: 1280px */
@media (width < 1280px) { } /* strictly less than */
/* Range in single expression */
@media (768px <= width <= 1280px) { } /* between 768 and 1280 */
@media (600px < width < 900px) { } /* strictly between */
/* Also works for height, resolution etc. */
@media (height >= 500px) { }
@media (resolution >= 2dppx) { }
/* Browser support: Chrome 113+, Firefox 63+, Safari 16.4+ */
Container Queries — The Next Step
@media queries respond to the viewport.
Container queries (@container) respond to the
parent element's size — making components truly self-contained and reusable:
A card component always becomes full-width at viewport 640px — even if the card is in a narrow sidebar where it should stay vertical.
(card horizontal)
(card also horizontal — wrong!)
The card becomes horizontal when its own parent is wide enough — stays vertical in a narrow sidebar, goes horizontal in wide main content.
(card horizontal ✓)
(card vertical ✓)
/* Step 1: Define a containment context */
.card-wrapper {
container-type: inline-size; /* enables width-based container queries */
container-name: card; /* optional: named container */
}
/* Step 2: Query the container, not the viewport */
@container (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 120px 1fr; /* horizontal when container ≥ 400px */
}
}
/* Named container query */
@container card (min-width: 600px) {
.card-title { font-size: 1.5rem; }
}
/* Range syntax works here too */
@container (width >= 400px) { }
/* container-type values */
.wrapper { container-type: inline-size; } /* width only */
.wrapper { container-type: size; } /* width + height */
.wrapper { container-type: normal; } /* disable */
/* Browser support: Chrome 105+, Firefox 110+, Safari 16+ */
Quick Reference
| Feature / Query | Syntax | Use for |
|---|---|---|
| min-width | @media (min-width: 768px) |
Mobile-first breakpoint — ≥ 768px |
| max-width | @media (max-width: 767px) |
Desktop-first breakpoint — ≤ 767px |
| Range (new) | @media (width >= 768px) |
Cleaner syntax, same effect |
| Double range | @media (600px <= width <= 1200px) |
Target a specific width band |
| Dark mode | @media (prefers-color-scheme: dark) |
Apply dark theme styles |
| Reduced motion | @media (prefers-reduced-motion: reduce) |
Disable/simplify animations |
| Touch device | @media (pointer: coarse) |
Larger tap targets, no hover-only UI |
| Mouse device | @media (hover: hover) and (pointer: fine) |
Enable hover interactions |
@media print |
Hide nav/ads, show URLs | |
| High-DPI | @media (min-resolution: 2dppx) |
Serve @2x images |
| Container | @container (min-width: 400px) |
Component responds to its own parent width |
Live Responsive Demo
This grid automatically adapts as the page width changes — 1 column on mobile, 2 on tablet, 3 on desktop. Resize your browser to see it reflow:
1 col → 2 col → 3 col
grid-template-columns: 1fr → 1fr 1fr → repeat(3,1fr) via @media min-width
Try It Yourself
All major media query patterns in one editor. Resize the preview pane or try changing the breakpoint values:
Quick Check — Chapter 39
min-width media queries for larger screens:/* base mobile */ .grid { grid-template-columns: 1fr }@media (min-width: 768px) { .grid { grid-template-columns: 1fr 1fr } }Desktop-first — write base styles for wide screens, then strip back with
max-width:/* base desktop */ .grid { grid-template-columns: 1fr 1fr 1fr }@media (max-width: 767px) { .grid { grid-template-columns: 1fr } }Why mobile-first is recommended:
1. Mobile devices download and parse only the base styles + applicable query styles — smaller payload
2. Desktop-first forces mobile to download all the complex desktop styles then override them — wasted bytes
3. Encourages thinking about the minimum viable layout first — better UX discipline
4. Aligns with how CSS Grid and Flexbox naturally work — simple/linear layouts first, then complex
@media (prefers-reduced-motion: reduce)This matches when the user has set their operating system to reduce motion (Windows: Settings → Ease of Access → Display → Show animations in Windows; macOS: System Settings → Accessibility → Display → Reduce motion).
The recommended pattern is to disable or significantly reduce all animations and transitions:
@media (prefers-reduced-motion: reduce) { * { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; scroll-behavior: auto !important; } }This is an important accessibility feature — vestibular disorders, epilepsy, and motion sensitivity can make large or fast animations physically harmful to some users. Always respect this preference in production CSS.
@media queries respond to the viewport
(the browser window) — properties like width, height, orientation, color-scheme. They are good for
layout changes that affect the page as a whole.@container queries respond to the element's own
containing parent — letting components change their layout based on how much space they have been
given, not the overall viewport.Example of the difference: A product card component placed in a 3-column main layout should display horizontally (image left, text right). The same card in a 1-column sidebar should display vertically (image top, text below). With @media, the card can't know where it is — it only knows the viewport is 1200px. With @container, the card responds to its direct parent's width — narrow sidebar = vertical layout, wide main = horizontal.
When to use each:
— @media: page-level layout (nav, sidebar, multi-column), dark mode, print, accessibility preferences
— @container: reusable components that need to adapt to their placement context
min-/max- prefixes:Old:
@media (min-width: 768px) → New: @media (width >= 768px)Old:
@media (max-width: 1280px) → New: @media (width <= 1280px)The biggest advantage is double-ended ranges in a single expression:
Old:
@media (min-width: 768px) and (max-width: 1280px)New:
@media (768px <= width <= 1280px)Operators available:
<, >,
<=, >=. The old syntax is
still valid and widely used — the new syntax is an addition, not a replacement. Browser support: Chrome
113+, Firefox 63+, Safari 16.4+.
This means
@media (min-width: var(--bp-md)) does NOT work — the
browser cannot evaluate it because var() has not been resolved yet.Workarounds:
1. SCSS variables:
$bp-md: 768px; @media (min-width: $bp-md) { } — preprocessor replaces
them before the browser sees the CSS2. PostCSS / CSS-in-JS: replace at build time
3. Hard-code breakpoints and document them as comments at the top of your CSS — simpler and more maintainable than it sounds
4. @custom-media (future CSS):
@custom-media --bp-md (min-width: 768px); — defined at the top, then
@media (--bp-md) { }. Browser support is pending.
- @media syntax:
@media [type] [and] (feature) { }. Media type is optional (defaults to all). Most queries only need a feature. - Key media features:
width/height(with min-/max-),orientation,prefers-color-scheme,prefers-reduced-motion,hover,pointer,resolution, print. - Mobile-first = base styles for mobile +
min-widthqueries for larger screens. Recommended. Desktop gets more styles added, mobile gets smallest download. - Standard breakpoints: 640px (sm), 768px (md), 1024px (lg), 1280px (xl), 1536px (2xl). Design-driven breakpoints ("where does the layout break?") are better than fixed device sizes.
- Logical operators:
and(both must match), comma/or(either),not(negates). - Range syntax (Level 4):
@media (width >= 768px)and@media (600px <= width <= 1200px)— cleaner and supports single-expression ranges. - Custom properties in @media: Do NOT work — variables are runtime, media conditions are parse-time. Use SCSS variables or hardcoded px values.
- @container queries: Respond to parent element size, not viewport. Requires
container-type: inline-sizeon parent. Essential for truly reusable components. - Accessibility: Always handle
prefers-reduced-motionto protect users with vestibular disorders. Usepointer: coarsefor larger touch targets.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.