Media query

On this page 7

A media query is a CSS construct that applies a block of styles only when a condition is true about the output device or user environment, such as a minimum viewport width, a landscape orientation, a high-resolution screen or a preference for reduced motion. Media queries are the foundation of responsive web design and are defined in the W3C Media Queries specifications.

In CSS, a media query is usually written with the @media at-rule, but the same syntax also appears in the media attribute of HTML link and source elements and in the JavaScript matchMedia method. In every case, the browser evaluates the condition continuously and switches styles as soon as the environment changes.

How a media query is evaluated

A media query consists of an optional media type and one or more media features in parentheses, combined with logical operators. The browser evaluates the whole expression to true or false, and only true queries apply their rules.

A typical example is @media (min-width: 48em) { ... }, which applies its rules when the viewport is at least 48 em wide. The range syntax from Media Queries Level 4 allows the clearer form @media (width >= 48em) and two-sided ranges such as (30em <= width < 60em), now supported in all major browsers.

Media queries do not add specificity. Rules inside a matching query compete in the cascade exactly like rules outside it, so source order decides between equally specific selectors. This is why mobile-first stylesheets place wider-screen queries after the base styles.

Media types and media features

Only three media types remain meaningful today: all, screen and print. Older types such as handheld or tv are deprecated. Most of the expressive power comes from media features, which describe the viewport, the device or the user’s preferences.

FeatureTests forTypical use
width, heightViewport dimensionsLayout breakpoints
orientationPortrait or landscape viewportRearranging media-heavy layouts
resolutionPixel density, for example 2dppxServing sharper background images
hover, pointerInput precision and hover capabilityLarger targets for touch input
prefers-color-schemeLight or dark system preferenceDark mode styles
prefers-reduced-motionUser request to minimize animationDisabling parallax and large transitions
prefers-contrastRequest for more or less contrastStronger borders and text colors
Commonly used media features

The user preference features are as important as dimensions. Respecting prefers-reduced-motion helps people with vestibular disorders, and it supports the WCAG guidance on animation from interactions. Interaction features such as (hover: none) describe capabilities rather than device names, which is more reliable than guessing from screen width.

Choosing breakpoints and units

A breakpoint is the value at which a media query changes the layout. Good breakpoints are chosen where the content starts to break, not to match particular phone or tablet models, because device sizes change every year.

SituationRecommended approachReason
New responsive siteMobile-first with min-width queriesBase styles stay simple, enhancements add up
Text-heavy layoutBreakpoints in em unitsLayouts scale with user font size settings
Component inside variable containersContainer query instead of media queryResponds to the container, not the viewport
Fluid typographyclamp with viewport units, few queriesSmooth scaling without stepwise jumps
Print stylesheet@media print blockHide navigation, adjust colors and page breaks
Decision guide for breakpoint strategy

Em-based breakpoints have a practical advantage: in media queries, 1em refers to the browser’s initial font size, typically 16 pixels, not to the root element’s styled size. When a user increases the default font size, em breakpoints shift accordingly, so the layout switches to a narrower arrangement before text becomes cramped.

Most sites need three to five layout breakpoints. Many smaller adjustments are better handled by flexible layout methods such as CSS grid with auto-fit columns or flexbox wrapping, which adapt continuously without any query.

Media query compared with container query

The most important neighboring concept is the container query. Both apply conditional styles, but they observe different things.

AspectMedia queryContainer query
Condition sourceViewport, device, user preferencesSize or style of an ancestor container
Syntax@media@container with container-type on the ancestor
Best forPage-level layout and global preferencesReusable components in varied slots
User preference featuresSupportedNot applicable
Browser supportUniversal for decadesBroad in current browsers
Media queries and container queries compared

The two are complementary rather than competing. A page layout typically uses media queries to decide how many columns exist, while a card component uses container queries to adapt to whichever column it lands in. Preferences such as dark mode and reduced motion remain media query territory.

Common mistakes

Media query problems usually come from overlapping ranges, wrong assumptions about devices or a missing viewport declaration.

  • Missing viewport meta tag: without width=device-width, mobile browsers render at a desktop width of about 980 pixels and width queries never match.
  • Overlapping or gapped ranges: using max-width 768px and min-width 768px together makes both apply at exactly 768 pixels; range syntax avoids this.
  • Device-specific breakpoints: queries targeting a particular phone model age quickly and miss everything in between.
  • Using width to detect touch: large tablets and small laptops break the assumption; pointer and hover features are more reliable.
  • Duplicated rules in many queries, which makes stylesheets hard to maintain; custom properties changed inside queries keep overrides small.

In simple terms

A media query is a rule that says when a style should apply. It works like an instruction such as this. If the screen is narrow, stack everything in one column. If the screen is wide, place it side by side.

Media queries can also follow personal settings. A phone in dark mode can get a dark page. A person who asked for less animation can get a calmer page. In short, one website adjusts itself to each screen and each person.

A practical example

A news website builds its article pages mobile-first. Base styles show a single column with 1.125 rem body text. A query at min-width 40em adds a sidebar for related stories, and a query at 64em widens the margins and enlarges headlines. A prefers-color-scheme: dark block swaps a handful of custom properties for background and text colors, and a print block hides navigation and advertising.

When readers raise their browser’s default font size, the em-based breakpoints shift, so the sidebar appears only when there is actually room for it. A prefers-reduced-motion query removes the animated headline ticker for readers who disabled animations. The result is one stylesheet serving phones, laptops, dark mode and printed pages, with no separate mobile site to maintain.