CSS Media Query Syntax

What You Learn From This Page

  • How the @media rule conditionally adds declarations to the CSS cascade.
  • How media types differ from media features such as width, hover, and orientation.
  • How to write classic min/max conditions and modern comparison range syntax.
  • How and, comma-separated lists, and not combine or negate queries.
  • How to respond to pointer, hover, color-scheme, motion, contrast, and forced-color preferences.
  • How print rules, linked stylesheets, CSS nesting, and JavaScript matching work.
  • How specificity, cascade layers, and source order continue to operate inside queries.
  • How to choose, organize, debug, and test media queries in production CSS.

Introduction

CSS media queries apply style rules only when a description of the current media environment matches. The condition can ask about available width or height, orientation, display medium, input precision, hover capability, color preferences, motion preferences, and other characteristics exposed by the browser. When the condition is false, the enclosed rules do not participate. When it is true, those rules enter the normal CSS cascade.

Media queries are best known for responsive width breakpoints, but their purpose is broader. A print query can remove interactive navigation from paper output. A reduced-motion query can replace movement with an immediate state change. Pointer and hover queries can add optional feedback suited to an input capability. These conditions let one semantic document adapt without inventing separate markup for every environment.

Good media-query syntax is only part of the task. Production CSS also needs meaningful conditions, predictable boundaries, low-specificity selectors, and verification between breakpoints. Flexible layout should handle continuous resizing wherever possible; media queries should express genuine changes in structure, behavior, or user preference.

The Basic @media Rule

The simplest form contains the @media at-rule, a condition in parentheses, and a block of ordinary CSS rules.

@media (min-width: 48rem) {
  .layout {
    grid-template-columns: 1fr 1fr;
  }
}

The browser evaluates whether the width of the media context is at least 48rem. If it matches, the declaration becomes a candidate for every element matching .layout. It still has to compete through origin, importance, layer order, specificity, scope proximity where applicable, and source order.

A Media Query Is a Conditional Gate

Think of the query as a gate around a group of style rules. It does not change HTML, create elements, or execute a sequence of commands. The browser continuously reevaluates relevant conditions when the environment changes, such as when a window is resized, a device rotates, print preview opens, or a system preference changes.

The rules inside a matching query are not automatically stronger than rules outside it. A query controls eligibility, while the cascade controls which eligible declaration wins. Keeping those responsibilities separate makes debugging much easier.

Media Types and Media Features

A media type describes a broad output category. Current practical types are all, screen, and print. A media feature asks about a characteristic such as width, height, orientation, hover, pointer, or prefers-reduced-motion.

@media screen and (min-width: 48rem) {
  .navigation {
    display: flex;
  }
}

Here screen is the media type and min-width is a media feature. For ordinary responsive screen layouts, the type is often omitted because @media (min-width: 48rem) already expresses the relevant condition.

The all Media Type

all applies to every media type and is effectively the default when no type is written. These queries are equivalent for normal use:

@media all and (min-width: 40rem) {
  .panel { padding: 2rem; }
}

@media (min-width: 40rem) {
  .panel { padding: 2rem; }
}

Omitting unnecessary syntax makes responsive rules easier to scan. Write a media type when the output medium itself is part of the requirement.

The screen Media Type

screen addresses screen-like output. Older stylesheets often begin every responsive rule with only screen and, but modern projects rarely need that ceremony. Width, input, and preference features can normally stand alone.

Use screen when a rule must explicitly exclude print and the distinction makes the stylesheet clearer. Do not assume screen means desktop; phones, tablets, televisions, and browser windows all produce screen media.

The print Media Type

Print queries adapt a page for paper or PDF generation. They can remove controls that cannot function on paper, restore natural heights, reveal link destinations, avoid clipped scroll regions, and improve pagination.

@media print {
  nav,
  .advertisement,
  .interactive-controls {
    display: none;
  }

  body {
    color: #000;
    background: #fff;
    font-size: 12pt;
  }
}

Always inspect browser print preview. Screen layouts with sticky sidebars, fixed heights, and independent scroll panes frequently need more than a few hidden elements.

Classic min-width Syntax

min-width matches when the media width is greater than or equal to the specified value. It is the common direction for a mobile-first architecture because wider enhancements become active as space grows.

.course-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
}

@media (min-width: 48rem) {
  .course-list {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

The unit is required for a nonzero length. Relative units such as rem often communicate text-related layout thresholds well, while pixels are also valid.

Classic max-width Syntax

max-width matches when width is less than or equal to the specified value. It is common in desktop-first CSS, where compact rules override the wide baseline.

.course-list {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
}

@media (max-width: 48rem) {
  .course-list {
    grid-template-columns: 1fr;
  }
}

Max-width is not inherently obsolete or inaccessible. The key is to use a consistent direction, flexible base dimensions, and compact modes that preserve essential content and actions.

Mobile-First Query Ordering

In a mobile-first sequence, the base works at narrow widths and min-width conditions are usually placed from smaller to larger thresholds. At a wide viewport, several queries may match simultaneously, so later rules win when selectors have equal cascade weight.

.cards { grid-template-columns: 1fr; }

@media (min-width: 40rem) {
  .cards { grid-template-columns: repeat(2, 1fr); }
}

@media (min-width: 64rem) {
  .cards { grid-template-columns: repeat(3, 1fr); }
}

At 70rem both conditions match, and the later three-column declaration wins. This progression should remain deliberate rather than relying on accidental ordering.

Desktop-First Query Ordering

Desktop-first CSS begins with the wide state and often orders max-width rules from larger thresholds toward smaller ones. As space shrinks, progressively more rules apply.

.cards { grid-template-columns: repeat(3, 1fr); }

@media (max-width: 64rem) {
  .cards { grid-template-columns: repeat(2, 1fr); }
}

@media (max-width: 40rem) {
  .cards { grid-template-columns: 1fr; }
}

Projects can mix query directions for justified exceptions, but each component should have a clear baseline. Arbitrary overlap makes the cascade difficult to reason about.

Modern Comparison Syntax

Media Queries Level 4 provides comparison operators that often read more naturally. A classic minimum-width condition can be written as a direct relationship.

@media (width >= 48rem) {
  .layout {
    grid-template-columns: 16rem minmax(0, 1fr);
  }
}

The condition says that width is greater than or equal to 48rem. Likewise, (width < 48rem) matches widths below the boundary. Check the project's browser-support policy before converting an older production codebase, but current engines support this syntax broadly.

Modern Range Syntax

A bounded interval can place the media feature between two comparisons.

@media (40rem <= width < 64rem) {
  .dashboard {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

This expresses a half-open range: width is at least 40rem and below 64rem. Classic syntax would use (min-width: 40rem) and (max-width: ...), often with a slightly adjusted upper boundary. Range syntax makes inclusion and exclusion explicit without fractional-pixel workarounds.

Avoid Accidental Boundary Overlap

The pair (max-width: 48rem) and (min-width: 48rem) both match exactly 48rem. That can be intentional if source order resolves a shared boundary, but it often surprises developers who expected separate ranges.

Modern comparisons can divide the states clearly with (width < 48rem) and (width >= 48rem). When classic syntax is required, document the convention used by the project and test values on both sides of every boundary.

Combine Conditions with and

The and keyword requires every connected condition to match.

@media (min-width: 40rem) and (max-width: 64rem) {
  .layout {
    grid-template-columns: 1fr 1fr;
  }
}

CSS media queries do not use JavaScript's &&. Add parentheses around individual feature expressions and use the keyword between them. Keep compound queries short enough that their purpose remains obvious.

Create OR Logic with a Query List

A comma-separated media-query list acts as logical OR. The block applies when any complete query in the list matches.

@media (max-width: 38rem), (orientation: portrait) {
  .secondary-panel {
    position: static;
  }
}

Be careful with broad alternatives. Portrait orientation includes many widths, including large tablets and tall desktop windows. Confirm that either side of the OR independently justifies the same style change.

Negate a Query with not

not negates a media query. A simple example can apply interactive controls outside print output.

@media not print {
  .interactive-controls {
    display: flex;
  }
}

Negation in complex query lists can be less intuitive because it applies to a complete query expression. Prefer a positive condition when it communicates the requirement more clearly, and test negated combinations in target browsers.

What only Means

The only keyword was historically used to keep very old user agents from interpreting a media type while ignoring unsupported feature syntax. A familiar legacy form is @media only screen and (min-width: 48rem).

Modern browsers understand media queries, so only is generally unnecessary. Existing code can retain it harmlessly, but new stylesheets usually gain nothing from adding it.

Width and Height Features

width and height describe the viewport for ordinary screen media. Width is the more common layout condition, while height is valuable for interfaces constrained vertically, such as dialogs, fixed toolbars, maps, and application workspaces.

@media (height < 42rem) {
  .dialog {
    max-block-size: 90dvh;
    overflow: auto;
  }
}

Do not rely on height conditions to force text-heavy sections into fixed viewports. Mobile browser controls and software keyboards can change visible height dynamically, so content flow and bounded scrolling remain important.

Orientation Queries

The orientation feature matches portrait when height is at least width and landscape when width exceeds height. It describes the viewport relationship, not necessarily how a physical device is being held.

@media (orientation: landscape) and (height < 32rem) {
  .hero {
    min-block-size: auto;
  }
}

Use orientation only when that relationship causes a real design need. Width and height often identify the actual constraint more precisely, especially in resizable windows, split-screen modes, and foldable contexts.

Hover Capability

The hover feature reports whether the primary input mechanism can conveniently hover. Values are hover and none. Use it for optional effects, not for essential access.

@media (hover: hover) {
  .card:hover {
    border-color: var(--accent);
    transform: translateY(-2px);
  }
}

The card must still expose its content and actions through activation and keyboard focus. A touchscreen laptop may have several inputs, so one query cannot fully describe every interaction available to the user.

Pointer Precision

The pointer feature describes the primary pointing device as none, coarse, or fine. A coarse pointer may justify larger targets or more spacing, while a fine pointer may support denser optional controls.

@media (pointer: coarse) {
  .icon-button {
    min-inline-size: 2.75rem;
    min-block-size: 2.75rem;
  }
}

Build an accessible baseline before specializing. Do not shrink controls below usable dimensions merely because pointer: fine matches.

any-hover and any-pointer

hover and pointer describe the primary mechanism. Their any-hover and any-pointer counterparts ask whether any available input has the capability. These features help in mixed environments, but they can also produce combinations that are difficult to translate into a single interface assumption.

Use them for narrowly scoped enhancements and preserve operation through touch and keyboard. Capability detection is more reliable than assuming an input from screen width, but it still requires inclusive design.

Preferred Color Scheme

prefers-color-scheme can match dark or light according to the user's environment preference.

@media (prefers-color-scheme: dark) {
  :root {
    --surface: #161a1f;
    --text: #f4f7fa;
    --border: #718096;
  }
}

Centralized custom properties make theme adaptation easier than repeating selectors inside the query. Verify contrast, form controls, images, syntax highlighting, and focus states in every supported scheme. A manual site theme may intentionally override the system preference.

Reduced Motion Preference

prefers-reduced-motion: reduce indicates that the user wants nonessential motion reduced. Replace large transitions, parallax, automatic movement, and decorative animation while preserving understandable state feedback.

@media (prefers-reduced-motion: reduce) {
  html { scroll-behavior: auto; }

  .card,
  .dialog {
    animation: none;
    transition: none;
  }
}

Avoid a careless universal override that breaks progress indicators or hides state transitions without an alternative. Review each motion pattern according to its purpose and potential impact.

Contrast and Forced Colors

prefers-contrast can request more or less contrast where supported. forced-colors: active identifies an active forced-color mode, commonly associated with high-contrast settings. These features support targeted improvements, but the default design should already meet contrast and focus requirements.

@media (prefers-contrast: more) {
  .button { border-width: 2px; }
}

@media (forced-colors: active) {
  .status-icon { forced-color-adjust: auto; }
}

Test with the actual platform mode. Decorative backgrounds and color-only states can disappear when user-agent colors replace authored colors.

Resolution and Display Characteristics

Media features can query resolution and other display characteristics, but CSS resolution queries should not replace responsive image selection. The browser can make better resource decisions through srcset, sizes, and image-set functions.

Use display-related queries only when a style genuinely depends on that characteristic. Avoid building device detection from a chain of screen, resolution, width, and orientation assumptions; future hardware and windowing modes will invalidate it.

Media Queries Do Not Change Specificity

A selector inside a media rule retains its normal specificity. In this example, the ID rule can beat the class rule even when the query matches:

#course-card { color: #b00020; }

@media (min-width: 48rem) {
  .course-card { color: #005a9c; }
}

Do not respond by making responsive selectors increasingly specific. Keep selectors simple and fix ownership, order, or architecture. Cascade layers can also establish intentional precedence without specificity escalation.

Source Order Still Resolves Equal Rules

When two matching declarations have equal origin, importance, layer, specificity, and scope proximity, the later declaration wins. At 70rem, both min-width blocks below match, so the second width is used.

@media (min-width: 40rem) {
  .panel { inline-size: 25rem; }
}

@media (min-width: 60rem) {
  .panel { inline-size: 37.5rem; }
}

Order queries consistently and avoid duplicating the same property across distant files when one component owns the behavior.

Media Queries and Cascade Layers

A rule's cascade layer is evaluated independently of its media condition. A matching declaration in an earlier layer can still lose to a declaration in a later layer even if the later rule is outside a media query.

@layer base, components, utilities;

@layer components {
  @media (min-width: 48rem) {
    .card { padding: 2rem; }
  }
}

Place responsive changes in the layer that owns the component instead of creating a universal responsive layer that unexpectedly overrides unrelated architecture.

Organizing Media Queries

One approach groups all conditions near the end of a stylesheet. Another keeps each component's queries next to its base rules. Component-local organization often improves ownership because a developer can understand the full responsive behavior without searching through a global breakpoint section.

Grouped queries can work in a small stylesheet or design-token architecture. Whichever pattern the project chooses, use consistent thresholds, naming, ordering, and comments that explain non-obvious reasons rather than restating syntax.

CSS Nesting with Media Queries

Modern CSS nesting allows a media rule to appear inside a style rule, keeping an enhancement close to its component.

.card {
  padding: 1rem;

  @media (min-width: 48rem) {
    padding: 2rem;
  }
}

The nested syntax is convenient but should not hide a large number of conditions inside one selector. Confirm support requirements and toolchain behavior, especially in projects that process CSS through older preprocessors or minifiers.

Conditional Stylesheets with link

The HTML media attribute can associate an external stylesheet with a condition.

<link rel="stylesheet" href="print.css" media="print">

This is useful for a substantial print stylesheet or specialized medium. It does not guarantee that an unmatched resource will never be fetched, and splitting ordinary responsive styles across many conditional files can make maintenance and loading behavior harder to understand.

The media Attribute on style

A style element can also have a media condition.

<style media="screen and (min-width: 48rem)">
  .layout { display: grid; }
</style>

This is valid, but regular @media rules in an owned stylesheet are usually easier to search, cache, test, and maintain. Use the attribute when document architecture provides a clear reason.

Match the Same Condition in JavaScript

The window.matchMedia() API lets JavaScript observe a media-query condition when behavior, not only presentation, must change.

const compact = window.matchMedia('(width < 48rem)');

function updateMode(event) {
  console.log(event.matches ? 'compact' : 'expanded');
}

updateMode(compact);
compact.addEventListener('change', updateMode);

Prefer CSS when only visual layout changes. JavaScript width logic can duplicate breakpoints, cause flashes, and become stale. Use matchMedia for behavior that truly needs script awareness, and share query values through a documented contract.

Media Queries vs Container Queries

A media query generally responds to the viewport or user environment. A container query responds to a qualifying ancestor's size or style. A card placed in a narrow sidebar on a wide display needs local adaptation that a viewport query cannot infer.

.card-region { container-type: inline-size; }

@container (min-width: 30rem) {
  .card {
    grid-template-columns: 9rem minmax(0, 1fr);
  }
}

Use media queries for page shells, print, and user preferences. Use container queries where a reusable component owns the decision based on its allocated space.

Media Queries vs Fluid CSS

Not every size change needs a conditional rule. Grid can fit a variable number of columns, Flexbox can wrap, and clamp() can bound fluid type or spacing.

.cards {
  display: grid;
  grid-template-columns: repeat(
    auto-fit,
    minmax(min(100%, 16rem), 1fr)
  );
  gap: clamp(0.75rem, 2vw, 1.5rem);
}

Use a media query when the composition should deliberately change, such as moving from one content column to a sidebar shell. Use fluid CSS for continuous adaptation within a composition.

Real-World Sidebar Pattern

A narrow-first page can stack its navigation and article, then introduce columns when both regions have useful space.

.docs-layout {
  display: grid;
  gap: 1.25rem;
}

@media (min-width: 60rem) {
  .docs-layout {
    grid-template-columns: 16rem minmax(0, 1fr);
    gap: 2rem;
  }
}

The zero-minimum flexible track helps prevent intrinsic content such as code or tables from forcing the grid wider than its container. Descendants still need an intentional wrap or local scrolling policy.

Real-World Navigation Pattern

CSS can switch between compact and persistent navigation presentation, but the compact mode also needs accessible behavior.

.nav-links { display: none; }
.menu-button { display: inline-flex; }

@media (min-width: 50rem) {
  .nav-links {
    display: flex;
    gap: 1rem;
  }

  .menu-button { display: none; }
}

The button must control a usable menu with an accessible name, expanded state, keyboard operation, and appropriate focus management. Media syntax cannot supply interaction semantics by itself.

Choose Breakpoints from Content

A breakpoint should exist because content or interaction needs a different arrangement. Resize until a navigation row wraps poorly, fields become too narrow, a sidebar damages reading measure, or a toolbar loses its action hierarchy. That point is more durable than a copied phone or tablet width.

Exact-width queries such as @media (width: 768px) are technically valid but rarely useful because they match only one value. Responsive interfaces need stable ranges and fluid behavior between them.

Avoid Device-Specific Features

Legacy CSS may use device-width in an attempt to identify hardware. Modern responsive design normally cares about the available layout viewport, which can change through windows, split screens, zoom, browser UI, and embedding.

Do not combine width, pixel ratio, and orientation to guess a device model. Query the condition the design actually needs. If the requirement concerns pointer precision, use pointer; if it concerns local component width, use a container query.

Common Syntax Errors

Media features normally require parentheses. @media min-width: 600px is invalid; write @media (min-width: 600px). A media type and feature require and, as in @media screen and (min-width: 600px). JavaScript operators such as && and || do not replace media-query syntax.

Nonzero lengths require units, so (min-width: 600) is invalid while (min-width: 600px) and (min-width: 40rem) are valid. Browser developer tools usually show invalid queries or declarations as ignored, making the console and Styles panel useful first checks.

Debugging a Query That Does Not Work

First confirm that the condition actually matches using responsive mode or the browser console. Then check whether the rule is parsed, whether its stylesheet loaded, and whether another declaration wins through layer order, specificity, importance, or source order. Inspect the computed property rather than assuming the media query failed.

Verify the viewport meta tag on mobile pages, units, boundary operators, selector accuracy, and nested syntax support. Temporarily apply an obvious harmless property to determine whether the block matches, then remove the diagnostic rule after finding the cause.

Testing Media Queries

Test immediately below, at, and above each threshold. Then drag continuously through the complete supported range to expose awkward widths not represented by a named breakpoint. Include narrow desktop windows, wide phones, portrait and landscape modes, short heights, and very large displays.

Test 200 percent zoom, larger text, long translations, loading and error states, keyboard focus, touch interaction, print preview, dark mode, reduced motion, and forced colors where supported. A query is correct only when the resulting experience remains usable, not merely when its condition parses.

Media Query Syntax Reference

SyntaxMeaning
@media (min-width: 48rem)Width is at least 48rem
@media (max-width: 48rem)Width is at most 48rem
@media (width >= 48rem)Modern minimum comparison
@media (width < 48rem)Width is below 48rem
@media (40rem <= width < 64rem)Width falls inside a half-open range
andEvery connected condition must match
Comma-separated listAny complete query may match
notNegates a complete query
screenScreen media type
printPrinted or previewed output
(hover: hover)Primary input can conveniently hover
(pointer: coarse)Primary pointer has limited precision
(prefers-reduced-motion: reduce)User requests less motion

Common Mistakes and Better Approaches

MistakeBetter Approach
Missing feature parenthesesWrite (min-width: 48rem)
Using &&Combine conditions with and
Using device model breakpointsChoose thresholds from content needs
Exact-width matchingDesign for stable ranges
Overlapping boundaries by accidentUse explicit comparison ranges
One query every few pixelsUse Grid, Flexbox, and fluid values
Making hover essentialUse hover only as an enhancement
Hiding essential compact contentStack, disclose, or reorganize it
Highly specific responsive selectorsKeep component selectors simple
Assuming a matching rule must winInspect the complete cascade
Using viewport queries for local cardsUse container queries where ownership is local
Testing only preset devicesTest continuously and across preferences

Common Interview Questions

What is the basic media-query syntax? Use @media, a media condition, and a block of CSS rules: @media (min-width: 48rem) { ... }.

What does min-width mean? It matches when the media width is greater than or equal to the specified value and is commonly used for mobile-first enhancement.

What does max-width mean? It matches when width is less than or equal to the specified value and is commonly used for desktop-first simplification.

How are multiple conditions combined? Use and when every condition must match. Use a comma-separated query list when any complete query may match.

What is modern range syntax? It uses comparison operators around a feature, such as (width >= 48rem) or (40rem <= width < 64rem).

Can media queries detect user preferences? Yes. Examples include preferred color scheme, reduced motion, contrast, and forced-color conditions.

Does a media query override specificity? No. Matching only makes declarations eligible; normal cascade rules still determine the winner.

When should container queries be used instead? Use them when a reusable component should respond to the dimensions or styles of its containing context rather than the viewport.

Practical Review Checklist

  • Use media queries for meaningful environment or composition changes.
  • Keep the baseline complete before conditional enhancements apply.
  • Choose breakpoints from content behavior rather than device names.
  • Use a consistent min-width or max-width progression per component.
  • Prefer modern range syntax when it clarifies inclusion boundaries.
  • Use and, query lists, and not with explicit intent.
  • Keep essential interactions independent of hover capability.
  • Respect color, motion, contrast, and forced-color preferences.
  • Provide deliberate print behavior for exportable content.
  • Remember that specificity, layers, and source order still apply.
  • Keep responsive selectors simple and near their component owner.
  • Use fluid CSS before adding many closely spaced breakpoints.
  • Use container queries for locally responsive reusable components.
  • Test every boundary, intermediate widths, zoom, and dynamic states.
  • Inspect computed styles when a matching query appears ineffective.

Key Takeaway

A media query asks a question about the current output environment. If the condition matches, its declarations join the normal cascade; if it does not, they remain ineligible. The familiar width query is only one part of the language, which also covers print, height, orientation, input capabilities, and user preferences.

Write conditions that express real design needs, make boundaries unambiguous, and keep selectors easy to override. Let Grid, Flexbox, intrinsic sizing, and fluid values handle continuous adaptation, then use media queries for structural transitions and environmental preferences that cannot be expressed fluidly. Test both the condition and the resulting experience across widths, input modes, accessibility settings, and print output.