Fact-checked by Grok 2 weeks ago

Media queries

Media queries are a feature of CSS, , and that allow authors to test and query values or features of the or —such as width, , color capabilities, or user preferences—independent of the document itself, enabling the conditional application of styles to create responsive and adaptive web experiences. The concept of media-dependent styling originated in 4.0 in 1997, which introduced basic media types for linking stylesheets, but it was the CSS3 Media Queries module—first drafted in 2001 and published as a W3C Candidate Recommendation in 2002—that expanded this into a full querying mechanism for device characteristics. This module achieved W3C Recommendation status on June 19, 2012, solidifying media queries as a cornerstone of modern . Subsequent levels, including Media Queries Level 4 (Candidate Recommendation Draft, 2021) and Level 5 (Working Draft, 2021), with Level 3 updated as Recommendation in 2024, have extended the specification with additional features for , scripting environments, and container-based queries. At their core, media queries are expressed using the CSS @media at-rule, which combines one or more media types (such as screen for visual displays, print for paged media, or the default all for all types) with optional media features—range-based or discrete conditions like width (viewport width in CSS pixels), orientation (portrait or landscape), prefers-color-scheme (light or dark mode), or prefers-reduced-motion (to minimize animations for users with vestibular disorders). These elements are linked by logical operators including and, or, not, and only, allowing complex conditions such as @media (min-width: 768px) and (orientation: landscape). The syntax supports nesting within other at-rules and programmatic testing via the matchMedia() API in JavaScript, facilitating dynamic style adjustments. Media queries are fundamental to , enabling layouts to adapt seamlessly across desktops, tablets, mobiles, and other devices without requiring separate stylesheets, while also supporting by respecting user settings like reduced data or modes. Their widespread support—fully implemented since around 2012—has made them indispensable for creating flexible, user-centric websites that perform efficiently in diverse environments.

Fundamentals

Syntax

Media queries in CSS are declared using the @media at-rule, which has the formal syntax @media <media-query-list> { <stylesheet> }. Here, <media-query-list> consists of one or more comma-separated <media-query>s, where commas imply a logical OR between the queries, and the curly braces enclose the styles that apply when the condition is true. This structure allows conditional application of CSS rules based on device characteristics. A <media-query> is composed of an optional logical modifier (not or only), an optional <media-type> (such as screen or print), and zero or more <media-feature> expressions combined with logical operators. The formal grammar for a <media-condition>, which groups ANDed queries, is defined as <media-condition> ::= <media-not> | <media-in-parens> [ <media-and>* | <media-or>* ], where <media-and> uses the and keyword to conjoin conditions, and <media-or> uses commas for disjunction. Logical operators include not for negation (applied at the query level), and for conjunction within a condition, and implicit or via comma separation in lists. Media features within queries often use range notation to specify thresholds, enclosed in parentheses for expressions like (min-width: 600px) or (max-width: 1200px). Modern range syntax, introduced in , supports comparison operators such as >, <, >=, and <= directly, as in (width >= 600px and width <= 1200px), providing a concise alternative to prefixed min/max forms. In contemporary CSS, following the CSS Nesting Module Level 1 (published as a Working Draft in 2023), media queries can be nested within style rules using the nesting selector & to reference the parent selector. For instance, @media (min-width: 600px) { & { property: value; } } applies the nested styles to the parent rule only when the condition holds, enhancing modularity without repetition. If a media query contains an invalid component, such as an unrecognized feature or syntax error, the entire query is treated as not all, rendering the condition false and causing the associated styles to be ignored. This error handling ensures robust parsing without cascading failures in the stylesheet.

Basic Principles

Media queries are a CSS module that enables authors to apply styles conditionally based on the type of media or specific characteristics of the device or user agent rendering the document. They extend the concept of media types from earlier CSS specifications by incorporating expressions that test conditions related to media features, such as display dimensions or interaction capabilities. This allows for tailored styling without requiring separate documents for different contexts. A media query evaluates to true if the specified media type matches the current rendering environment and all included expressions for media features are satisfied; otherwise, it evaluates to false. When a query is true, the associated CSS rules are applied as part of the normal stylesheet processing; if false, those rules are ignored, ensuring styles only activate under matching conditions. Queries can be combined in lists separated by commas, where the overall result is true if at least one individual query is true, providing flexibility in conditional logic. Media queries primarily target the browser's rendering environment, including the viewport—the visible area of the document—and device-specific properties, independent of the content itself. For instance, features like width reference the viewport size, while others may query fixed device attributes, allowing styles to adapt to the user's display context dynamically. This focus on the rendering environment ensures queries respond to real-time changes, such as window resizing, without reloading the page. Within the CSS cascade, media queries integrate seamlessly, with their rules subject to the same specificity, inheritance, and precedence rules as other declarations. This means conditional styles can override or be overridden by non-conditional ones based on standard CSS mechanisms, promoting modular and maintainable code. Media queries were introduced as part of , building on media type support from and , and require no special setup beyond basic CSS knowledge for implementation. Browser support for media queries is fundamental to their adoption, with core functionality available in major browsers since the late 2000s—Chrome from version 4 (2008), Firefox from 3.5 (2009), Safari from 3.2 (2008), and Internet Explorer from 9 (2011)—and now reaching 95% global usage across devices. This broad compatibility supports progressive enhancement principles, where baseline styles load universally, and enhanced styles apply only when queries match, ensuring graceful degradation on unsupported or mismatched environments.

Media Types

Standard Media Types

Media types in CSS media queries are predefined keywords that identify broad categories of output devices or media to which stylesheets or style rules apply, allowing authors to target specific rendering environments. The standard media types, as defined in the W3C's CSS Media Queries Level 3 recommendation, consist of four primary keywords: all, screen, print, and speech. These types enable conditional application of CSS rules based on the device's general characteristics, with updates in CSS Media Queries Level 5 (Working Draft, latest publication December 18, 2021) maintaining the core set while enhancing related features for finer control. As of November 2025, Media Queries Level 5 remains a Working Draft. The all media type matches every type of device and serves as the default when no media type is explicitly specified in a query. For instance, omitting the type in an @media rule, such as @media (max-width: 600px) { ... }, implicitly targets all devices. The screen media type applies to visual, non-paged displays, including computer monitors, smartphones, tablets, and televisions, making it the most commonly used for web content viewed on screens. An example usage is @media screen { body { background-color: white; } }, which applies styles only to screen-based rendering. The print media type targets paged, opaque output media, such as physical printers or browser print preview modes, where content is formatted for sequential pages rather than continuous scrolling. It supports specialized styling, like adjusting margins or fonts for better ink efficiency, as in @media print { h1 { font-size: 12pt; } }. The speech media type is designed for aural output devices, such as speech synthesizers that render content as spoken audio, though it is rarely implemented or used due to limited support and the preference for more advanced audio features. Queries using speech do not support certain units like pixels, rendering size-based expressions invalid. Media types can be combined with media features to form more specific queries, such as @media screen and (orientation: portrait) { ... }, but the type itself provides the initial broad categorization.

Deprecated and Vendor-Specific Types

In CSS2, several media types were introduced to target specific output devices, but many have since been deprecated due to their limited practical utility and overlap with the more versatile screen type. The tty type, intended for fixed-pitch character grid devices like teletypes or terminals, was deprecated because such hardware became rare in modern computing environments. Similarly, the tv type for television displays and the projection type for projected presentations were deprecated owing to evolving display technologies and insufficient differentiation from general screen-based rendering. The handheld type, aimed at small portable devices, was also deprecated as device categories blurred and more precise media features emerged to handle varying form factors. Vendor-specific extensions have occasionally filled gaps in early standards, particularly in WebKit-based browsers. The -webkit-device-pixel-ratio media feature, introduced to detect high-DPI displays (such as ) by measuring device pixels per CSS inch, was a proprietary WebKit prefix that gained widespread use before standardization. It has since been superseded by the standard resolution media feature using the dppx unit (device pixels per CSS pixel), allowing cross-browser compatibility without prefixes. The braille and embossed media types targeted niche tactile feedback devices for the visually impaired, with braille for refreshable braille displays and embossed for paged braille printers. These were deprecated in Media Queries Level 4 due to their extremely limited adoption and the preference for media features that better address accessibility needs across diverse devices. To migrate from these deprecated types, developers should replace them with equivalent media features, such as resolution for density-related targeting or pointer for interaction capabilities, which provide finer control without relying on broad device categories. Historical browser support for these types often exhibited quirks, particularly in early implementations. Internet Explorer versions prior to 9 provided inconsistent parsing of non-standard types like handheld and projection, frequently defaulting to screen behavior in quirks mode. Early WebKit engines, such as those in Safari 3 and iOS 2, supported vendor-prefixed variants but ignored or mismatched deprecated types like tty and tv due to incomplete adherence to CSS2 specifications.

Media Features

Display Dimensions

Display dimensions in CSS media queries refer to media features that test the size and shape of the rendering viewport or page area, enabling styles to adapt based on physical or logical display characteristics. These features primarily include width, height, orientation, and aspect-ratio, which allow developers to respond to varying screen sizes and orientations without relying on fixed device assumptions. Unlike earlier approaches that targeted static device properties, modern implementations focus on the dynamic viewport to better accommodate user interactions like resizing or scrolling. The width and height media features query the dimensions of the targeted display area, such as the viewport for screen media or the page box for print. For instance, min-width: 768px can apply styles optimized for tablet-sized viewports, ensuring layouts expand appropriately on larger displays. These are range-type features, supporting queries like width >= 600px or 400px <= width <= 700px, and accept length units including absolute values like pixels (px) or relative units like em and rem, where em is relative to the element's font size and rem to the root font size. Historically, device-width and device-height were used to reference the full device screen size, independent of the viewport, as in @media (device-width: 800px). However, these are deprecated in favor of width and height, which provide more flexible, viewport-based targeting that adjusts to dynamic changes like browser chrome or orientation shifts. This shift promotes responsive designs that prioritize the actual rendering area over fixed hardware specs. The orientation feature determines the display's posture, yielding portrait if the height is greater than or equal to the width, or landscape otherwise, as in @media (orientation: landscape) { ... }. This discrete feature triggers style changes during device rotation, commonly used to adjust layouts for vertical versus horizontal viewing. It directly compares viewport dimensions, ensuring seamless adaptation without additional scripting. Complementing these, the aspect-ratio feature tests the ratio of width to height, expressed as a <ratio> value like 16/9 for displays, with syntax such as @media (aspect-ratio: 16/9). As a range feature, it supports inequalities like aspect-ratio > 16/9, aiding in optimizations for specific screen proportions, such as video-friendly ratios. This helps maintain proportional scaling across diverse devices. Range queries enhance all dimension features by allowing prefixed qualifiers (min- for greater than or equal, max- for less than or equal) or direct operators (>, <, <=, >=), providing precise control over conditions. Length units in these queries resolve relative to the initial context, ensuring consistency across media types. As of 2025, browser support for dynamic viewports in mobile contexts has improved significantly, with features like width and height now reliably accounting for transient UI elements such as collapsible address bars or virtual keyboards. This aligns with the adoption of dynamic viewport units (dvh, svh, lvh) in CSS, extending media query accuracy for mobile-first responsive designs without legacy device-width fallbacks.

Color and Environment

Media features related to color and environment allow authors to adapt content based on a device's color capabilities, resolution, and environmental rendering conditions, such as contrast preferences or scanning methods. These features enable targeted styling for diverse output devices, from low-bit-depth displays to high-dynamic-range screens. The color media feature specifies the number of bits per color component supported by the , with a value of 0 indicating a non-color device. For example, @media (color: 8) targets devices with at least 8 bits per color component, allowing authors to adjust formats or color schemes for optimal rendering on limited palettes. This feature, defined as a type, supports comparisons like (color >= 8) to ensure compatibility with color-rich environments. Similarly, the media reports the number of bits per in a monochrome frame buffer, returning 0 for non-monochrome devices. An example query, @media (monochrome: 2), applies styles to displays with at least 2 bits per , such as early e-ink readers, where authors might simplify designs to . As a , it facilitates thresholds like (monochrome >= 2) for broader monochrome support. The media feature measures the of the , incorporating page zoom effects, and can yield infinite for vector-based outputs like . For instance, @media (resolution: 300dpi) optimizes styles for high-resolution printers by adjusting font sizes or image resolutions accordingly. This range feature accepts units like dpi, dpcm, or dppx, enabling precise targeting such as (resolution >= 2dppx) for high-density screens. The color-gamut media feature queries the device's supported , with discrete values srgb (standard ), p3 (wide P3 gamut), or rec2020 ( for ultra-high definition). For example, @media (color-gamut: p3) enables vibrant colors on wide-gamut displays like modern smartphones or monitors, optimizing images or gradients for enhanced color reproduction. This feature supports adaptation to advanced display technologies. Introduced in Media Queries Level 5, the dynamic-range media feature assesses a device's overall capacity for , , and , distinguishing between standard (typical SDR displays) and high (HDR-capable devices with elevated peak and ). A query like @media (dynamic-range: high) allows enhanced visuals, such as brighter highlights or deeper blacks, on modern televisions or monitors supporting . This discrete feature indirectly addresses device-level and without separate metrics, prioritizing content adaptation for immersive environments. Complementing device capabilities, the prefers-contrast media feature detects user preferences for contrast levels, with values including no-preference, less, more, or custom. For example, @media (prefers-contrast: more) enables higher adjustments for , such as bolder text outlines, responding to environmental needs like low-light viewing. This discrete , also from , ensures content respects user settings without altering core device properties. The prefers-color-scheme media feature allows adaptation based on the user's preferred , with discrete values light, dark, or no-preference. For instance, @media (prefers-color-scheme: dark) applies dark theme styles, inverting colors or using appropriate palettes to match and reduce . This Level 5 feature is essential for seamless theme integration across operating systems. The prefers-reduced-motion media feature respects user preferences to minimize motion, with values no-preference (default) or reduce. An example query @media (prefers-reduced-motion: reduce) disables or simplifies animations and transitions, benefiting users with vestibular disorders or those sensitive to movement. This discrete feature promotes accessibility by honoring OS-level settings like "Reduce Motion" on or . The forced-colors media feature indicates when a enforces a limited, system-defined color palette, such as in high-contrast modes for . With values none (standard colors) or active (forced mode enabled), a query like @media (forced-colors: active) applies compatible styles, using CSS system colors like Canvas or CanvasText to maintain readability. This discrete feature supports by detecting OS-level overrides, as seen in Windows . The inverted-colors media feature detects if the user agent or OS inverts colors for accessibility, with values none or inverted. For example, @media (inverted-colors: inverted) adjusts styles to account for inversion, preventing issues like unreadable text on inverted backgrounds. This discrete feature aids compatibility with system-wide inversion settings. For niche environmental adaptations, the scan media feature describes the output device's scanning method, with progressive for sequential line rendering (common in LCDs) or interlace for alternating lines (legacy CRTs and some TVs). An example, @media (scan: interlace), mitigates visual artifacts like flickering by adjusting content for interlaced video displays. As a discrete feature, it remains relevant for broadcast or older television contexts.

Interaction and Pointer

Media features related to interaction and pointer allow authors to query the user's input methods and device capabilities, enabling adaptive styling for diverse interaction paradigms such as touch, mouse, or keyboard inputs. These features are particularly useful in responsive design to differentiate between precise cursor-based interactions and coarser touch gestures, ensuring optimal user experiences across devices. The pointer media feature tests the presence and precision of the primary pointing device, such as a or . It accepts three discrete values: none (no pointing device available), coarse (low-precision device like a fingertip on touchscreens), and fine (high-precision device like a mouse cursor). For example, the query @media (pointer: coarse) targets touch devices, allowing designers to enlarge interactive elements for easier tapping. Introduced to handle scenarios with multiple input methods, the any-pointer media feature extends this by evaluating all available pointing devices rather than just the primary one. It shares the same values as pointer: none, coarse, and fine, but a query like @media (any-pointer: fine) matches if at least one device offers fine precision, accommodating setups like laptops with touchscreens. This feature supports mixed-input environments by preventing overly conservative designs that assume only coarse interaction. The hover media feature determines whether the primary input mechanism can hover over elements without activating them, distinguishing devices like mice from touch interfaces. Its discrete values are none (no hover capability, as in touch devices) and hover (hover supported, as in cursor-based inputs). An example is @media (hover: hover), which applies styles relying on :hover pseudo-classes for desktop previews, avoiding them on mobile to prevent accidental triggers. Complementing hover, the any-hover media feature checks if any available input supports hovering, making it suitable for devices with varied peripherals. Like hover, it uses none or hover values; for instance, @media (any-hover: hover) enables hover effects if even a secondary device like an external is connected. This allows for more inclusive designs in multi-input contexts without disabling features prematurely. The media feature assesses the frequency at which the output device can refresh content appearance, influencing the suitability of dynamic effects like animations. It supports discrete values: none (no updates possible), slow (infrequent updates, such as e-ink displays), and fast (high-frequency updates for smooth motion). For example, @media (update: fast) can apply fluid animations on standard screens, while @media (update) (boolean form) excludes static displays altogether. The media feature detects whether the output device renders content on a fixed grid, such as character-cell terminals, versus bitmap displays. It is a range feature treated as a mq-boolean, with value 1 for grid-based devices and 0 otherwise. A query like @media (grid: 1) adjusts layouts for single-column, text-only environments typical of phones or terminals emulating grid output. Though less common in modern bitmap-dominated devices, it ensures compatibility with legacy or specialized systems. Finally, the scripting media feature queries the availability of scripting languages like in the . Its discrete values are none (scripting disabled or unavailable), initial-only (scripting allowed only during initial load), and enabled (full scripting support). For instance, @media (scripting: enabled) applies styles assuming dynamic content generation, with fallbacks via @media (scripting) for any support level. This feature aids in , providing graceful degradation when scripting is restricted.

Usage and Examples

Responsive Web Design

leverages media queries to adapt layouts dynamically to a wide range of device screen sizes, ensuring optimal across phones, tablets, and desktops. This approach prioritizes flexibility by using CSS features like relative units and conditional rules to reflow content without requiring separate fixed-width designs. The mobile-first approach begins with base styles optimized for the smallest screens, such as smartphones, and progressively enhances the layout using min-width media queries for larger viewports. This method promotes performance by loading minimal CSS initially and adding complexity only as needed, reducing initial payload for users. Common breakpoints include 480px for devices, 768px for tablets, and 1024px for desktops, selected based on where content naturally reflows or user interaction patterns shift, rather than strict device specifications. For instance, a fluid grid can use percentages and max-width properties in base styles, then apply media queries to adjust widths for better utilization of space on wider screens. An example is:
css
.container {
  max-width: 100%;
  width: 100%;
}

@media (min-width: 600px) {
  .container {
    width: 80%;
    margin: 0 auto;
  }
}
This ensures the scales smoothly while centering content on tablets and desktops. Media queries also enable adaptations in modern systems like Flexbox and CSS Grid. With Flexbox, the default vertical stacking on mobile can switch to horizontal via flex-direction: row at a breakpoint like 768px, ideal for navigation menus. Similarly, CSS Grid can alter grid-template-columns from a single column to multiple ones, such as repeat(3, 1fr) at 1024px, to create responsive card or article layouts that fill available space efficiently. Integration with the meta tag is essential for proper scaling on devices: <meta name="viewport" content="width=device-width, initial-scale=1"> instructs s to set the viewport width to the device's actual width, allowing media queries based on dimension features like width to function accurately. Testing responsive designs involves tools to emulate various screen sizes and orientations. Tools like Firefox's Responsive Design Mode or Chrome's Device Toolbar allow designers to toggle breakpoints in real-time, inspect layout changes, and verify adaptations without physical devices. Media queries enable web authors to tailor styles for print and other non-screen media types, such as paged outputs or speech synthesis, by targeting specific device characteristics like the 'print' media type or features such as resolution and monochrome capabilities. For instance, the 'print' media type applies styles when content is rendered for physical printing or PDF generation, allowing adjustments to font sizes, margins, and layouts to optimize readability on paper. A common example is scaling body text to 12pt for legibility while increasing line heights and margins to prevent overcrowding:
css
@media print {  
  body {  
    font-size: 12pt;  
    line-height: 1.5;  
    margin: 1in;  
  }  
}  
This ensures the document fits standard page sizes without excessive scaling by the browser. In paged media like , controlling page breaks is essential to avoid splitting content awkwardly across pages. Properties such as page-break-before and page-break-after (now largely superseded by break-before and break-after in modern specifications) dictate where breaks occur, such as forcing a new page before headings or avoiding breaks within tables. For example:
css
h1 {  
  page-break-before: always;  
}  
table {  
  page-break-inside: avoid;  
}  
These rules help maintain logical flow in printed documents, particularly for reports or articles. Practical applications often involve hiding non-essential elements like navigation menus or sidebars to conserve and , while optimizing visuals for conditions. A typical hides interactive components:
css
@media [print](/page/Print) {  
  [nav](/page/NAV), .sidebar, [button](/page/Button) {  
    [display](/page/Display): none;  
  }  
}  
For monochrome printers, the monochrome media detects bits per pixel in the output , allowing styles to adjust for black-and-white output, such as using only black text and simple to reduce usage. This supports values from 0 (not monochrome) to 1 or higher bits per pixel. Beyond print, media queries address other outputs like with the 'speech' , which styles content for auditory rendering despite limited browser support. An example adjusts voice properties:
css
@media speech {  
  body {  
    voice-family: male;  
    voice-rate: medium;  
  }  
}  
This influences screen readers or text-to-speech engines, though adoption remains inconsistent across user agents. Legacy media types include '' for slideshows on projectors, which once adjusted styles for full-screen presentations but is now deprecated in favor of more flexible queries, and 'tty' for fixed-pitch text terminals like early consoles, recommending avoidance of units in favor of character-based sizing. Best practices recommend isolating print styles in separate CSS files linked via <link rel="stylesheet" media="print" href="print.css"> to minimize load times for screen users and facilitate maintenance. This approach, combined with testing in print preview modes, ensures compatibility across browsers and printers.

Advanced Topics

Container Queries

Container queries represent an advancement in CSS that allows styles to be applied based on the dimensions or other properties of a container , rather than the global or device characteristics. The @container at-rule enables this functionality, with a syntax such as @container (min-width: 400px) { .card { flex-direction: row; } }, which targets the container's size to conditionally style its descendants. This feature is defined in the CSS Conditional Rules Module Level 5, where the rule filters styles based on container conditions like size, style, or scroll-state. To establish an as a query , the container-type must be set on the , typically to inline-size to enable queries along the inline axis, or size for both inline and axes; the initial value is normal, which does not establish . Additionally, the container-name allows assigning a custom identifier to the , such as container-name: card-layout;, facilitating targeted queries like @container card-layout (min-width: 400px) { ... }. These , along with the shorthand container, are specified in the CSS Module Level 3. -relative length units further support this system, including cqi (1% of the 's inline ), cqb (1% of the 's ), and cqh (1% of the 's ), enabling sizing relative to the rather than fixed or viewport-based units. For instance, a child might use width: 50cqi; to scale proportionally within its . Unlike traditional media queries, which operate in a global context tied to the or device environment, container queries function locally within the defined container, promoting the creation of reusable, self-contained components that adapt independently of the overall page layout. This shift allows developers to modules, such as cards or sidebars, that respond to their immediate parent's available space, enhancing in responsive . As of 2025, container queries enjoy stable support across major browsers, including 105+, 110+, 16+, and 105+, with implementation beginning in 2023. A practical example involves a component within a flexible : the parent div is styled with container-type: inline-size;, and the query @container (min-width: 300px) { .card { display: flex; [gap](/page/Gap): 1cqi; } } rearranges the 's from to when the parent's width exceeds 300px, regardless of screen size. This approach ensures the behaves consistently when embedded in varying layouts, such as a narrow sidebar or a full-width .

Media Query Lists and Ranges

Media query lists allow authors to combine multiple media queries using comma separation, which implements logical OR semantics such that the list evaluates to true if at least one query is true. For instance, the rule @media screen and (min-width: 600px), print { body { font-size: 1.2em; } } applies styles when the device is a screen wider than 600 pixels or when rendering for media. An empty media query list is considered true by default. Range queries, introduced in Media Queries Level 4, enable concise expressions for bounded conditions using comparison operators such as <, >, <=, and >= within a range context. This syntax serves as a for combining minimum and maximum feature values; for example, @media (500px <= width <= 1200px) { .container { max-width: 80%; } } matches viewports between 500 and 1200 pixels wide without needing separate min-width and max-width queries. Ranges support negative values, though such queries typically evaluate to false in practical scenarios, like (width <= -100px). The keyword negates a media query or type, applying styles only when the condition is false; for example, @media not screen and (color) { body { background: white; } } targets non-color screens. Conversely, the keyword ensures compatibility with legacy user agents by hiding the query from those that do not fully support the syntax, preventing partial style application; @media only speech { p { voice-family: announcer; } } thus applies solely to speech in supporting browsers. These keywords can precede a media type or the entire query but cannot be used together. Media queries can be combined with container queries using the and to create conditional rules based on both global media features and container-specific ones, such as @media (prefers-reduced-motion: no-preference) and (container-type: size) { .element { animation: slide-in 0.5s; } }. This integration allows for more precise targeting without deep nesting. User agents evaluate media query lists from left to right, applying (true, false, or unknown) where unknown values propagate as false in two-valued contexts like final style application. For optimization, authors should group related queries into reusable custom media queries defined via @custom-media, reducing repetition and easing maintenance; for example, @custom-media --narrow (max-width: 480px); @media --narrow, print { ... } reuses the narrow condition across rules. However, as of November 2025, custom media queries lack native browser support and require preprocessing tools for use. Avoid excessive lists, as frequent re-evaluations during changes can impact rendering performance, particularly on resize events. As of 2025, range contexts from Media Queries Level 4 enjoy broad browser support, while features from Media Queries Level 5, including custom media queries, remain in Working Draft status since December 2021. These features enhance expressiveness for OR-based combinations without increasing parse complexity.

History and Standards

Development History

The development of media queries originated with the basic media types introduced in earlier CSS specifications, providing a for device-specific styling. The CSS Level 2 (CSS2) specification, published by the (W3C) as a Recommendation on May 12, 1998, first defined recognized media types such as "all" (suitable for all devices), "screen" (for color computer screens), and "print" (for paged, opaque material). These types allowed authors to link or import style sheets targeted to specific output using the @media rule or the media attribute in link elements, enabling rudimentary adaptation between screen display and printed output without querying detailed device properties. This limited capability addressed initial needs for multi-medium presentation but proved insufficient as web access expanded beyond desktops to diverse devices. The concept of media queries, extending media types with dynamic expressions, was formally proposed in the initial Working Draft of the CSS3 Media Queries Module on May 17, 2001, authored by of Software and Tantek Çelik of Corporation. The draft introduced media features like "width" ( or page-box width in length units), "height", and "color", combined with media types via logical operators (e.g., screen and (min-width: 25cm)), to scope style sheets based on device characteristics. This innovation was motivated by the emerging proliferation of and handheld devices in the early , which demanded adaptive rendering to reflow content and adjust layouts for varying screen sizes, resolutions, and capabilities, ensuring usability without separate document versions. Over the subsequent decade, the module underwent iterative refinement through multiple Working Drafts, reaching Candidate Recommendation status on July 27, 2010, and achieving W3C Recommendation status on June 19, 2012, which stabilized core features including range queries and feature detection for visual, paged, and other media. Browser implementations accelerated adoption, with providing early support starting in version 9.5 (released June 2008), enabling developers to test query-based styles on and . Apple followed with partial support in 3.1 (March 2008) and fuller implementation in 3.2 (November 2008), particularly leveraging WebKit's rendering for applications. introduced comprehensive support in 3.5 (June 2009), including features like and queries. These milestones were driven by key contributors including , a co-inventor of CSS, and Tantek Çelik, alongside collaborative efforts from browser vendors such as , Apple, and within the W3C CSS Working Group, with supplementary discussions in the community influencing related web standards.

Evolution and Current Status

The evolution of media queries has seen significant advancements since the initial CSS Media Queries Level 3, with Level 4 introducing enhanced interaction-related features to better support diverse input devices. Published as a Candidate Recommendation in September 2017, with updates through December 2021 and remaining at Candidate Recommendation status as of November 2025, Level 4 added the pointer media feature to query the accuracy of pointing devices (values: none, coarse, fine) and the hover media feature to detect hover capability (values: none, hover), enabling more precise adaptations for touch, , and other interfaces. These additions addressed limitations in earlier levels by allowing styles to respond to user interaction patterns without relying solely on screen size. Building on this, Media Queries Level 5, first published as a Working Draft on March 3, 2020, with ongoing refinements through 2023-2025, streamlined the specification by deprecating obsolete media types such as tty, tv, projection, handheld, braille, embossed, aural, and speech, urging authors to use media features instead for greater flexibility and future-proofing. It introduced new media features like dynamic-range (values: standard or high) to detect display capabilities for brightness, color depth, and contrast, and forced-colors (values: none or active) to handle high-contrast modes enforced by operating systems. Complementing these updates, the Container Queries Module was formalized as part of the CSS Containment Module Level 3, with a key Working Draft released in August 2022 and further advancements leading to a separate specification emphasis by 2023. This module defines the @container at-rule, allowing queries against a container's size, style, or other properties via container-type declarations (e.g., size or inline-size), enabling styles to adapt based on parent element dimensions rather than the viewport. By 2025, full implementation was achieved across major browsers, marking a shift toward modular, reusable design patterns. Browser adoption has progressed rapidly, with core media queries enjoying approximately 95% global support as of 2025, reflecting near-universal compatibility for foundational features like width and orientation queries. Container queries specifically reached strong coverage, supported in 106 and later (covering over 90% of users), 110 and later, and 16 and later, achieving about 92.5% global usage and enabling widespread responsive component design. Looking ahead, experimental extensions in 2025 include style queries within container queries, which allow conditioning styles on a container's computed properties (e.g., custom property values), currently in early implementation stages in select browsers like Chrome. Similarly, scroll-state queries, introduced in Chrome 133 in January 2025, enable detection of scroll behaviors such as stuck, snapped, or scrollable states via container-type: scroll-state, remaining in standards-track development with limited cross-browser availability. These innovations continue to expand media queries beyond static conditions, addressing gaps in dynamic, context-aware styling post the container era.

References

  1. [1]
    Media Queries Level 5 - W3C
    Dec 18, 2021 · This module extends and supersedes [MEDIAQUERIES-4] and its predecessor [MEDIAQUERIES-3], which themselves built upon and replaced CSS 2 § 7 ...Media Queries · Syntax · Interaction Media Features · Custom Media Queries
  2. [2]
    Media Queries - W3C
    Jul 8, 2002 · Media Queries extend the functionality of media types by allowing more precise labeling of style sheets. A Media Query consists of a media type ...Missing: history | Show results with:history
  3. [3]
    Media Queries Level 4 - W3C
    Dec 25, 2021 · Media Queries Level 4 describes the mechanism and syntax of media queries, media types, and media features. It extends and supersedes the features defined in ...
  4. [4]
  5. [5]
  6. [6]
  7. [7]
  8. [8]
  9. [9]
  10. [10]
  11. [11]
  12. [12]
    CSS Nesting Module - W3C
    Feb 14, 2023 · This module introduces the ability to nest one style rule inside another, with the selector of the child rule relative to the selector of the parent rule.Introduction · Nesting Style Rules · Nesting Selector: the & selector · Conformance
  13. [13]
  14. [14]
  15. [15]
  16. [16]
    Media Queries Level 3 - W3C
    May 21, 2024 · In the media queries syntax, the comma expresses a logical OR, while the ' and ' keyword expresses a logical AND. Here is an example of several ...Background · Media Queries · Syntax · Media features
  17. [17]
    Using media queries - CSS | MDN
    ### Summary of Media Queries Principles
  18. [18]
    CSS3 Media Queries | Can I use... Support tables for ... - CanIUse
    "Can I use" provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile web browsers.
  19. [19]
  20. [20]
    @media - CSS | MDN
    ### Definition
  21. [21]
    Media Queries Level 5
    Summary of each segment:
  22. [22]
  23. [23]
  24. [24]
    The Great WebKit Comparison Table - QuirksMode
    On this page I compare 21 WebKits in order to prove that there is no “WebKit on Mobile” and to figure out which one is the best.Missing: historical | Show results with:historical
  25. [25]
  26. [26]
  27. [27]
  28. [28]
  29. [29]
  30. [30]
  31. [31]
  32. [32]
  33. [33]
  34. [34]
  35. [35]
  36. [36]
  37. [37]
  38. [38]
  39. [39]
  40. [40]
  41. [41]
  42. [42]
  43. [43]
  44. [44]
  45. [45]
  46. [46]
    Breakpoints for Responsive Web Design in 2025 - BrowserStack
    Use mobile-first media queries: Structure your CSS using min-width queries to layer enhancements. This results in smaller initial payloads and better ...
  47. [47]
  48. [48]
    7 Media types - W3C
    Authors should not use pixel units with the "tty" media type. Intended for television-type devices (low resolution, color, limited-scrollability screens, sound ...
  49. [49]
    13 Paged media
    A page break must occur at (1) if, among the 'page-break-after' and 'page-break-before' properties of all the elements generating boxes that meet at this margin ...
  50. [50]
  51. [51]
    page-break-before - CSS - MDN Web Docs
    Oct 30, 2025 · The page-break-before CSS property adjusts page breaks before the current element.Try it · Syntax · Page break aliases
  52. [52]
    CSS Conditional Rules Module Level 5 - W3C
    Oct 30, 2025 · The container-type property establishes the element as a query container for certain types of queries. For size container queries, which require ...
  53. [53]
    CSS Containment Module Level 3 - W3C
    Aug 18, 2022 · This CSS module describes the contain property, which indicates that the element's subtree is independent of the rest of the page.Container Queries · Container Features · Container Relative Lengths... · APIs
  54. [54]
    CSS Container Queries (Size) | Can I use... Support ... - CanIUse
    Size queries in Container Queries provide a way to query the size of a container, and conditionally apply CSS to the content of that container.
  55. [55]
  56. [56]
  57. [57]
  58. [58]
  59. [59]
  60. [60]
  61. [61]
  62. [62]
  63. [63]
  64. [64]
    CSS Snapshot 2025 - W3C
    Sep 18, 2025 · This module defines APIs for parsing, serializing, and manipulating CSS, Media Queries, and Selectors. CSS Color Module Level 5 [CSS-COLOR-5] ...Introduction · Classification of CSS... · Requirements for Responsible... · Indices
  65. [65]
    Media queries - W3C
    May 17, 2001 · A media query consists of a media type and one or more expressions to limit the scope of a certain style sheet.Missing: development history
  66. [66]
    a short introduction to media queries in Firefox 3.5 - Mozilla Hacks
    Jun 15, 2009 · Media queries are currently supported by Firefox 3.5, Safari 3, and Opera 7 and later, with successive versions often adding support for ...Missing: history 1.2
  67. [67]
    CSS WG Blog – CSS3 Media Queries reaches Recommendation
    Jun 19, 2012 · The CSS Working Group has published Media Queries as a Recommendation. Media Queries allows authors to tailor the style that they want to apply ...Missing: Candidate | Show results with:Candidate
  68. [68]
  69. [69]
    CSS Containment Module Level 3
    Jun 20, 2024 · This document is governed by the 18 August 2025 W3C Process Document. ... Media Queries Level 5 . URL: https://drafts.csswg.org/mediaqueries-5 ...
  70. [70]
    CSS scroll-state() | Blog - Chrome for Developers
    Jan 15, 2025 · Published: Jan 15, 2025. Chrome 133 builds upon container queries by introducing scroll state container queries. The browser managed state ...
  71. [71]