Tutorials CSS Media Queries
Ch 39 / 60
Chapter 39 Intermediate 10 min read CSS

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.

What you'll learn
@media syntax and structure
Media types: screen, print, all
Media features: width, height, orientation, color-scheme…
Mobile-first vs desktop-first
Logical operators: and, or, not
Modern range syntax + container queries intro

@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:

@media screen and (min-width: 768px) { ... } ↑ at-rule ↑ media type ↑ media feature ↑ styles block
CSS — @media syntax variants
/* 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 / height
(min-width: 768px)
Viewport width/height. The most used media feature. Also: device-width (deprecated).
orientation
(orientation: landscape)
Portrait (height > width) or landscape (width > height).
aspect-ratio
(aspect-ratio: 16/9)
Ratio of viewport width to height.
prefers-color-scheme
(prefers-color-scheme: dark)
User's OS dark/light mode preference. Essential for dark mode.
prefers-reduced-motion
(prefers-reduced-motion: reduce)
User has requested less animation. Disable or simplify transitions.
prefers-contrast
(prefers-contrast: more)
User needs higher contrast. Increase text/background contrast.
hover
(hover: hover)
Device has hover capability (mouse). Use for hover-only interactions.
pointer
(pointer: coarse)
Pointer precision: none, coarse (touch), fine (mouse). Affects tap target sizes.
resolution
(min-resolution: 2dppx)
Pixel density for high-DPI / Retina screens.
color-gamut
(color-gamut: p3)
Display's colour gamut. Target wide-colour displays.
display-mode
(display-mode: standalone)
Whether the app is running as a PWA (standalone, fullscreen).
forced-colors
(forced-colors: active)
Windows High Contrast / forced colour mode is active.
CSS — common media features
/* 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:

✓ Mobile-first (recommended)
/* 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

Desktop-first (avoid for new projects)
/* 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):

640px
sm
768px
md
1024px
lg
1280px
xl
1536px
2xl
0px (mobile) 1920px+
0–639
640–767
sm
768–1023
md
1024–1279
lg
1280–1535
xl
1536+
2xl
CSS — common breakpoints (mobile-first)
/* 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:

and
Both conditions must be true. @media screen and (min-width: 768px) — screen AND at least 768px wide.
or / ,
Either condition must be true. A comma (,) or the keyword or works. @media (max-width: 600px), (orientation: portrait) — narrow OR portrait.
not
Negates the entire query. @media not print — everything except print. not requires a media type or must wrap a condition.
CSS — logical operators
/* 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:

Old syntax (still valid)
@media (min-width: 768px) { }
@media (max-width: 1280px) { }
@media (min-width: 768px)
    and (max-width: 1280px) { }
New range syntax ✓
@media (width >= 768px) { }
@media (width <= 1280px) { }
@media (768px <= width <= 1280px) { }
/* Elegant single expression! */
CSS — Level 4 range syntax
/* >= 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:

@media — viewport-relative

A card component always becomes full-width at viewport 640px — even if the card is in a narrow sidebar where it should stay vertical.

Main content
(card horizontal)
Sidebar
(card also horizontal — wrong!)
@container — parent-relative ✓

The card becomes horizontal when its own parent is wide enough — stays vertical in a narrow sidebar, goes horizontal in wide main content.

Main content
(card horizontal ✓)
Sidebar
(card vertical ✓)
CSS — @container queries
/* 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
Print @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:

Card 1
1 col → 2 col → 3 col
Card 2
Card 3
Card 4
Card 5
Card 6

grid-template-columns: 1fr → 1fr 1fr → repeat(3,1fr) via @media min-width

Free Resource
CSS3 Cheat Sheet — All Properties & Selectors
Complete reference covering all CSS media features, breakpoints and modern responsive techniques.
Download PDF

Try It Yourself

All major media query patterns in one editor. Resize the preview pane or try changing the breakpoint values:

Live Editor
✎ Editor
👁 Preview
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React and Node.js with real projects and placement support.
120+
Chapters
40 hrs
Content
10 Real
Projects
4.9 ⭐
Rating
HTML5CSS3JavaScriptReact.jsNode.jsTailwind CSSAI Tools

Quick Check — Chapter 39

Questions & Answers
Mobile-first — write base styles for the smallest screen, then add complexity with 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
The modern range syntax (CSS Media Queries Level 4) uses comparison operators instead of 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+.
CSS custom properties (variables) are runtime values — they are resolved after the CSS is parsed. Media query conditions are evaluated at parse time by the browser's style engine, before custom properties have been computed.

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 CSS
2. 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.
Multiple Choice Questions
Question 1 of 5
Which media query uses the modern range syntax to target widths between 600px and 900px (inclusive)?
Question 2 of 5
What media feature detects whether the primary pointing device is a touchscreen?
Question 3 of 5
For container queries to work, what CSS property must you set on the containing element?
Question 4 of 5
Which media query would correctly apply styles only for screens that are at least 768px wide AND in landscape orientation?
Question 5 of 5
Which approach correctly adds print styles that hide navigation and show link URLs?
Chapter Summary
  • @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-width queries 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-size on parent. Essential for truly reusable components.
  • Accessibility: Always handle prefers-reduced-motion to protect users with vestibular disorders. Use pointer: coarse for larger touch targets.
~10 min read
Intermediate level
Chapter 39 of 60

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel