Media queries are a feature of CSS, HTML, and JavaScript that allow authors to test and query values or features of the user agent or display device—such as viewport width, orientation, color capabilities, or user preferences—independent of the document itself, enabling the conditional application of styles to create responsive and adaptive web experiences.[1]
The concept of media-dependent styling originated in HTML 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.[2] This module achieved W3C Recommendation status on June 19, 2012, solidifying media queries as a cornerstone of modern web design. 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 accessibility, scripting environments, and container-based queries.[3][1][4]
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).[1] 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.[5][1]
Media queries are fundamental to responsive web design, enabling layouts to adapt seamlessly across desktops, tablets, mobiles, and other devices without requiring separate stylesheets, while also supporting accessibility by respecting user settings like reduced data or high contrast modes. Their widespread browser 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> }.[6] 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.[7] 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.[8] 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.[9] 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.[10]
Media features within queries often use range notation to specify thresholds, enclosed in parentheses for expressions like (min-width: 600px) or (max-width: 1200px).[11] Modern range syntax, introduced in Media Queries Level 4, supports comparison operators such as >, <, >=, and <= directly, as in (width >= 600px and width <= 1200px), providing a concise alternative to prefixed min/max forms.[12]
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.[13] 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.[14]
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.[15] This error handling ensures robust parsing without cascading failures in the stylesheet.[16]
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.[4]
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.[4][17]
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.[4][17]
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 CSS Level 3, building on media type support from CSS2 and HTML4, and require no special setup beyond basic CSS knowledge for implementation.[4][17]
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.[18][17]
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.[4]
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.[4] 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.[1]
The all media type matches every type of device and serves as the default when no media type is explicitly specified in a query.[4] For instance, omitting the type in an @media rule, such as @media (max-width: 600px) { ... }, implicitly targets all devices.[4]
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.[4] An example usage is @media screen { body { background-color: white; } }, which applies styles only to screen-based rendering.[4]
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.[4] It supports specialized styling, like adjusting margins or fonts for better ink efficiency, as in @media print { h1 { font-size: 12pt; } }.[4]
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.[4] Queries using speech do not support certain units like pixels, rendering size-based expressions invalid.[4]
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.[4]
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.[19][20]
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 Retina screens) 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.[19]
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.[21][22]
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.[20][23]
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.[1]
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.[24]
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.[25]
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.[26]
Complementing these, the aspect-ratio feature tests the ratio of width to height, expressed as a <ratio> value like 16/9 for widescreen 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.[27]
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 breakpoint conditions. Length units in these queries resolve relative to the initial viewport context, ensuring consistency across media types.[28]
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.[1]
The color media feature specifies the number of bits per color component supported by the output device, 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 image formats or color schemes for optimal rendering on limited palettes. This feature, defined as a range type, supports comparisons like (color >= 8) to ensure compatibility with color-rich environments.[29]
Similarly, the monochrome media feature reports the number of bits per pixel in a monochrome frame buffer, returning 0 for non-monochrome devices. An example query, @media (monochrome: 2), applies styles to grayscale displays with at least 2 bits per pixel, such as early e-ink readers, where authors might simplify designs to shades of gray. As a range feature, it facilitates thresholds like (monochrome >= 2) for broader monochrome support.[30]
The resolution media feature measures the pixel density of the output device, incorporating page zoom effects, and can yield infinite for vector-based outputs like print. 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.[31]
The color-gamut media feature queries the device's supported color space, with discrete values srgb (standard sRGB), p3 (wide P3 gamut), or rec2020 (Rec. 2020 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.[32]
Introduced in Media Queries Level 5, the dynamic-range media feature assesses a device's overall capacity for brightness, contrast ratio, and color depth, distinguishing between standard (typical SDR displays) and high (HDR-capable devices with elevated peak brightness and contrast). A query like @media (dynamic-range: high) allows enhanced visuals, such as brighter highlights or deeper blacks, on modern televisions or monitors supporting high dynamic range. This discrete feature indirectly addresses device-level contrast and brightness without separate metrics, prioritizing content adaptation for immersive environments.[33]
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 contrast adjustments for accessibility, such as bolder text outlines, responding to environmental needs like low-light viewing. This discrete feature, also from Level 5, ensures content respects user settings without altering core device properties.[34]
The prefers-color-scheme media feature allows adaptation based on the user's preferred color scheme, 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 system settings and reduce eye strain. This Level 5 feature is essential for seamless theme integration across operating systems.[35]
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 iOS or Android.[36]
The forced-colors media feature indicates when a user agent enforces a limited, system-defined color palette, such as in high-contrast modes for accessibility. 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 inclusive design by detecting OS-level overrides, as seen in Windows High Contrast.[37]
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.[38]
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.[39]
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.[22] 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 mouse or touchscreen.[40] 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).[40] 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.[41] 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 hybrid setups like laptops with touchscreens.[41] 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.[42] Its discrete values are none (no hover capability, as in touch devices) and hover (hover supported, as in cursor-based inputs).[42] 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 device supports hovering, making it suitable for devices with varied peripherals.[43] 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 mouse is connected.[43] This allows for more inclusive designs in multi-input contexts without disabling features prematurely.
The update media feature assesses the frequency at which the output device can refresh content appearance, influencing the suitability of dynamic effects like animations.[44] It supports discrete values: none (no updates possible), slow (infrequent updates, such as e-ink displays), and fast (high-frequency updates for smooth motion).[44] For example, @media (update: fast) can apply fluid animations on standard screens, while @media (update) (boolean form) excludes static displays altogether.
The grid media feature detects whether the output device renders content on a fixed grid, such as character-cell terminals, versus bitmap displays.[45] It is a range feature treated as a mq-boolean, with value 1 for grid-based devices and 0 otherwise.[45] 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.[46]
Finally, the scripting media feature queries the availability of scripting languages like JavaScript in the user agent.[47] Its discrete values are none (scripting disabled or unavailable), initial-only (scripting allowed only during initial load), and enabled (full scripting support).[47] For instance, @media (scripting: enabled) applies styles assuming dynamic content generation, with fallbacks via @media (scripting) for any support level. This feature aids in progressive enhancement, providing graceful degradation when scripting is restricted.[48]
Usage and Examples
Responsive Web Design
Responsive web design leverages media queries to adapt layouts dynamically to a wide range of device screen sizes, ensuring optimal user experience across mobile 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.[1]
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 mobile users.[49] Common breakpoints include 480px for mobile 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.[49]
For instance, a fluid grid can use percentages and max-width properties in base styles, then apply media queries to adjust container 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;
}
}
.container {
max-width: 100%;
width: 100%;
}
@media (min-width: 600px) {
.container {
width: 80%;
margin: 0 auto;
}
}
This ensures the layout scales smoothly while centering content on tablets and desktops.
Media queries also enable adaptations in modern layout 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 viewport meta tag is essential for proper scaling on mobile devices: <meta name="viewport" content="width=device-width, initial-scale=1"> instructs browsers to set the viewport width to the device's actual width, allowing media queries based on display dimension features like width to function accurately.
Testing responsive designs involves browser developer 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.[3][50] 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.[51] 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;
}
}
@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.[50]
In paged media like print, 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.[52][53] For example:
css
h1 {
page-break-before: always;
}
table {
page-break-inside: avoid;
}
h1 {
page-break-before: always;
}
table {
page-break-inside: avoid;
}
These rules help maintain logical flow in printed documents, particularly for reports or articles.[54]
Practical applications often involve hiding non-essential elements like navigation menus or sidebars to conserve ink and space, while optimizing visuals for print conditions. A typical rule hides interactive UI components:
css
@media [print](/page/Print) {
[nav](/page/NAV), .sidebar, [button](/page/Button) {
[display](/page/Display): none;
}
}
@media [print](/page/Print) {
[nav](/page/NAV), .sidebar, [button](/page/Button) {
[display](/page/Display): none;
}
}
For monochrome printers, the monochrome media feature detects bits per pixel in the output buffer, allowing styles to adjust for black-and-white output, such as using only black text and simple line art to reduce ink usage. This feature supports values from 0 (not monochrome) to 1 or higher bits per pixel.[4]
Beyond print, media queries address other outputs like speech synthesis with the 'speech' media type, which styles content for auditory rendering despite limited browser support.[51] An example adjusts voice properties:
css
@media speech {
body {
voice-family: male;
voice-rate: medium;
}
}
@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 'projection' 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 pixel units in favor of character-based sizing.[51]
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.[50] This approach, combined with testing in print preview modes, ensures compatibility across browsers and printers.[3]
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 parent container element, rather than the global viewport 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.[55]
To establish an element as a query container, the container-type property must be set on the parent, typically to inline-size to enable size queries along the inline axis, or size for both inline and block axes; the initial value is normal, which does not establish containment. Additionally, the container-name property allows assigning a custom identifier to the container, such as container-name: card-layout;, facilitating targeted queries like @container card-layout (min-width: 400px) { ... }. These properties, along with the shorthand container, are specified in the CSS Containment Module Level 3. Container-relative length units further support this system, including cqi (1% of the container's inline size), cqb (1% of the container's block size), and cqh (1% of the container's height), enabling sizing relative to the container rather than fixed or viewport-based units. For instance, a child element might use width: 50cqi; to scale proportionally within its parent.[56]
Unlike traditional media queries, which operate in a global context tied to the viewport 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 design modules, such as cards or sidebars, that respond to their immediate parent's available space, enhancing modularity in responsive design. As of 2025, container queries enjoy stable support across major browsers, including Chrome 105+, Firefox 110+, Safari 16+, and Edge 105+, with implementation beginning in 2023.[55][57]
A practical example involves a card component within a flexible grid: 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 card's content from stacked to horizontal when the parent's width exceeds 300px, regardless of screen size. This approach ensures the card behaves consistently when embedded in varying layouts, such as a narrow sidebar or a full-width section.[56]
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.[58] 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 print media.[58] An empty media query list is considered true by default.[58]
Range queries, introduced in Media Queries Level 4, enable concise expressions for bounded conditions using comparison operators such as <, >, <=, and >= within a range context.[12] This syntax serves as a shorthand 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.[12] Ranges support negative values, though such queries typically evaluate to false in practical scenarios, like (width <= -100px).[12]
The not 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.[59] Conversely, the only 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 media in supporting browsers.[60] These keywords can precede a media type or the entire query but cannot be used together.[59]
Media queries can be combined with container queries using the and operator 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; } }.[61] This integration allows for more precise targeting without deep nesting.
User agents evaluate media query lists from left to right, applying three-valued logic (true, false, or unknown) where unknown values propagate as false in two-valued contexts like final style application.[62] 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.[63] 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 viewport changes can impact rendering performance, particularly on resize events.[64]
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.[1][65] These features enhance expressiveness for OR-based combinations without increasing parse complexity.[66]
History and Standards
Development History
The development of media queries originated with the basic media types introduced in earlier CSS specifications, providing a foundation for device-specific styling.
The CSS Level 2 (CSS2) specification, published by the World Wide Web Consortium (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 media using the @media rule or the media attribute in HTML 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 Håkon Wium Lie of Opera Software and Tantek Çelik of Microsoft Corporation. The draft introduced media features like "width" (viewport 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.[67]
This innovation was motivated by the emerging proliferation of mobile and handheld devices in the early 2000s, which demanded adaptive rendering to reflow content and adjust layouts for varying screen sizes, resolutions, and capabilities, ensuring usability without separate document versions.[67]
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.[4]
Browser implementations accelerated adoption, with Opera providing early support starting in version 9.5 (released June 2008), enabling developers to test query-based styles on desktop and mobile.[18] Apple followed with partial support in Safari 3.1 (March 2008) and fuller implementation in Safari 3.2 (November 2008), particularly leveraging WebKit's rendering for iPhone applications. Mozilla introduced comprehensive support in Firefox 3.5 (June 2009), including features like orientation and resolution queries.[18][68]
These milestones were driven by key contributors including Håkon Wium Lie, a co-inventor of CSS, and Tantek Çelik, alongside collaborative efforts from browser vendors such as Opera, Apple, and Mozilla within the W3C CSS Working Group, with supplementary discussions in the WHATWG community influencing related web standards.[67][69]
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, mouse, and other interfaces.[3] 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.[1] 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.[33][37]
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.[56] 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.[70] By 2025, full implementation was achieved across major browsers, marking a shift toward modular, reusable design patterns.[57]
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 Chrome 106 and later (covering over 90% of users), Firefox 110 and later, and Safari 16 and later, achieving about 92.5% global usage and enabling widespread responsive component design.[57]
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.[71][72] These innovations continue to expand media queries beyond static conditions, addressing gaps in dynamic, context-aware styling post the container era.