Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 139 ยท Responsive Design

Media Queries

Apply CSS only when conditions match. Learn @media syntax, the modern range syntax, orientation, hover and pointer, prefers-* features and combining queries.

A media query wraps some CSS in a condition. The browser checks the condition, and only when it is true do the rules inside apply. "Is the screen at least 600 pixels wide?" "Is this device using a mouse?" "Has the user asked for less motion?" Each of those is a media query.

In the previous lesson you saw that fluid and intrinsic layouts handle a lot without any conditions at all. Media queries handle the rest: the moments when a layout should change shape, and the moments when the page should respect what the user's device or settings tell it.

The anatomy of a media query

A media query is an at-rule. It starts with @media, followed by a condition, followed by a block of ordinary CSS rules:

CSS
@media (width >= 600px) {
  .sidebar {
    display: block;
  }
}

The part in parentheses is a media feature: a property of the device or environment, like width, compared with a value. When the condition stops being true, for example because someone resizes the window, the rules stop applying immediately. No reload needed.

A media query does not add specificity. The rules inside are normal rules, and they compete in the cascade like any other. That means order matters: put your media queries after the base rules they override, or the base rules will win.

Your first media query

The query measures the preview pane, not your whole browser window, because the preview is a separate page with its own viewport. On a real site, width is the width of the browser's viewport.

Media types

Before the parentheses, you can name a media type. There are only three you will use:

  • screen: screens of any kind.
  • print: printed pages and print preview (see Print Styles).
  • all: everything. This is the default when you leave the type out.
CSS
@media print {
  nav, .ads { display: none; }
}

@media screen and (width >= 900px) {
  /* wide screens only, not paper */
}

Most of the time you leave the type out and only test features.

Width ranges: old and new syntax

Width is the feature you will query most. For years it was written with min-width and max-width:

CSS
@media (min-width: 600px) { /* 600px and wider */ }
@media (max-width: 599px) { /* narrower than 600px */ }

These still work everywhere, and you will see them in almost every existing codebase. But they read backwards ("min-width" means "the width is at least"), and they have a gap: what happens at 599.5px, which can occur on high-density screens and with zoom? Neither query matches.

The range syntax fixes both problems. You write real comparisons with <, <=, > and >=:

CSS
@media (width >= 600px) { /* 600px and wider */ }
@media (width < 600px)  { /* anything narrower than 600px, no gap */ }
@media (600px <= width < 900px) { /* a range between two values */ }

The range syntax works in every current major browser and has been widely available since 2023. Use it in new code unless you need to support older browsers.

Ranges that never overlap

You can also query height, and aspect-ratio (such as (aspect-ratio > 1)), the same way.

Which unit for breakpoints?

Pixels are the most common. Some developers prefer em in media queries, such as (width >= 40em). Inside a media query, em always means the browser's default font size (usually 16px), not the font size of any element. The advantage: if a user raises their default font size, em breakpoints move with it, so the layout switches to the roomier version sooner. Either choice is fine; just be consistent.

Orientation

orientation is portrait when the viewport is taller than it is wide, and landscape otherwise:

CSS
@media (orientation: landscape) {
  .hero { min-height: 60vh; }
}

Note that this is about the viewport, not the device. A desktop browser window can be portrait, and a phone keyboard popping up can turn a portrait viewport landscape. Width is usually a better guide for layout; orientation is useful for things like hero height.

Hover and pointer: what kind of input?

Not every device has a mouse. Interaction media features describe the input method:

  • hover: hover means the main input can hover (a mouse or trackpad). hover: none means it can't (a touchscreen).
  • pointer: fine means a precise pointer like a mouse. pointer: coarse means a finger. pointer: none means no pointer at all.
  • any-hover and any-pointer ask the same questions about any connected input, not just the main one. A tablet with a mouse plugged in has hover: none but any-hover: hover.

Two practical uses:

CSS
/* Only reveal extra controls on hover where hovering is possible. */
@media (hover: hover) {
  .card .actions { opacity: 0; }
  .card:hover .actions,
  .card:focus-within .actions { opacity: 1; }
}

/* Bigger tap targets for fingers. */
@media (pointer: coarse) {
  .toolbar button { min-height: 44px; }
}

Never hide something behind hover with no other way to reach it. Touch users can't hover, and keyboard users need focus styles. Notice the :focus-within in the example above.

User preference features

Operating systems let people choose dark mode, reduced motion, higher contrast and more. The prefers-* features let your CSS honor those choices:

  • prefers-color-scheme: dark or light: the user's theme. Covered fully in Dark Mode.
  • prefers-reduced-motion: reduce: the user wants less animation, often because motion makes them feel ill. See Motion and Performance.
  • prefers-contrast: more: the user wants stronger contrast.
  • forced-colors: active: a high-contrast mode is replacing your colors, as covered in Accessible CSS.
What does your device report?

Display and color features

Besides size and user preferences, media queries can ask about the display itself. These features are less common because modern screens answer them all the same way, but you will see them in older code and in print or e-paper work.

Feature Question it asks Typical value today
color How many bits per color channel does the device have? 0 means no color 8 on ordinary screens
color-index How many entries are in the device's color lookup table? 0 means it does not use one 0
monochrome How many bits per pixel in a monochrome (single-color) device? 0 means it is not monochrome 0 (a black-and-white e-paper device reports a positive number)
grid Is the device a grid-based one, such as a text terminal, rather than a bitmap screen? 0 on screens
resolution How dense are the pixels? Accepts dpi, dpcm and dppx (and the x alias for dppx) 1dppx to 3dppx
update Can the output change after the page loads? fast, slow or none fast on screens, none on print
overflow-block What happens when content is longer than the screen? scroll, paged or none scroll on screens, paged for print
dynamic-range Can the display show HDR brightness? standard or high standard, or high on HDR screens
inverted-colors Has the system inverted the colors? inverted or none none
light-level Is the ambient light dim, normal or washed? Not supported in browsers

Each of color, color-index, monochrome and resolution also has min- and max- forms (min-color: 8, max-resolution: 1dppx), and the modern range syntax works too: (color >= 8), (resolution >= 2dppx). A bare feature name is a yes/no test: (color) is true for any color device, and (monochrome) is true only for monochrome ones.

CSS
/* A color device: use the full palette */
@media (min-color: 8) { :root { --accent: #4f46e5; } }

/* A one-color display, such as some e-paper: rely on black, white and patterns */
@media (monochrome) {
  :root { --accent: black; }
  .chart-bar { background: repeating-linear-gradient(45deg, black 0 4px, white 4px 8px); }
}

/* Sharper images on dense screens */
@media (min-resolution: 2dppx) {
  .logo { background-image: url("[email protected]"); }
}

/* Honor a system-wide color inversion (an accessibility setting) */
@media (inverted-colors: inverted) {
  img, video { filter: invert(1); }
}

A few cautions:

  • inverted-colors is only implemented in Safari. When the system inverts all colors, pictures look wrong, so the rule above inverts them a second time. Treat it as a progressive enhancement.
  • light-level is in the Media Queries Level 5 draft, but browsers do not implement it. A query for it never matches, so do not build anything that depends on it.
  • Do not use device-width or device-height (the width of the whole screen, not the window). They are deprecated, and the layout should follow the viewport.
  • color-index and grid are essentially historical. Knowing they exist helps when you read old stylesheets; you will almost never write them.

To see what your device answers, ask the browser directly with window.matchMedia(query).matches:

Test display media features

On a typical laptop screen the plain (color) and (min-color: 8) tests report yes, while color-index, monochrome, grid and light-level report no. Resolution tests depend on your screen's pixel density.

Combining conditions

Real queries often test more than one thing. You have four tools:

  • and: both conditions must be true.
  • A comma: either query may match. It works like or between whole queries.
  • or: either condition may match, inside one query (newer syntax, supported alongside the range syntax).
  • not: reverses a condition.
CSS
/* Wide AND landscape */
@media (width >= 700px) and (orientation: landscape) { ... }

/* Print OR narrow screens */
@media print, (width < 500px) { ... }

/* Same idea with "or" inside one query */
@media (width < 500px) or (orientation: portrait) { ... }

/* Anything that is NOT a touch-only device */
@media not (hover: none) { ... }

When a query gets long, step back. A long chain of conditions is often a sign that a simpler, intrinsic layout (or a container query) would do the job better.

Media queries outside @media

The same conditions appear in a few other places:

  • On a <link> element: <link rel="stylesheet" href="print.css" media="print">. The browser still downloads the file, but at low priority and without blocking the page.
  • In <picture> and <source> elements, to choose between images (see Responsive Images).
  • In JavaScript, with window.matchMedia(), which returns an object whose matches property is true or false, and which can tell you when the answer changes.
Media queries in JavaScript

Use matchMedia only when JavaScript truly needs to know, for example to switch a component's behavior. For anything visual, keep the logic in CSS.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which query matches viewports that are at least 600px wide?

    width >= 600px reads exactly as it sounds. The older equivalent is min-width: 600px, not max-width.
  2. 2. Why is (width < 600px) safer than (max-width: 599px) for the range below a 600px breakpoint?

    With high-density screens and zoom, the viewport can be a fractional width. The range syntax leaves no gap between width < 600px and width >= 600px.
  3. 3. You want hover-only effects to appear only on devices whose main input can hover. Which feature do you test?

    hover: hover is true when the primary input, such as a mouse, can hover. Touchscreens report hover: none.
  4. 4. What does a comma between two media queries mean?

    A comma-separated list of queries matches when any one of them matches, like or.
  5. 5. Do media queries change the specificity of the rules inside them?

    A media query is only a condition. The rules inside have their normal specificity, which is why media queries usually come after the base rules they override.

Summary

  • @media (condition) { ... } applies its rules only while the condition is true, and updates live as things change.
  • Media queries add no specificity, so place them after the rules they override.
  • Prefer the range syntax, such as (width >= 600px) and (400px <= width < 700px); min-width and max-width still work.
  • hover, pointer and their any- versions describe the input device; never hide content behind hover alone.
  • prefers-color-scheme, prefers-reduced-motion and prefers-contrast let you respect user settings.
  • Combine queries with and, commas, or and not; use matchMedia() when JavaScript needs the same answer.

Next: Mobile-First CSS, a workflow for writing responsive styles that start small and grow.