@media
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
* Some parts of this feature may have varying levels of support.
The@mediaCSSat-rule can be used to apply part of a style sheet based on the result of one or moremedia queries. With it, you specify a media query and a block of CSS to apply to the document if and only if the media query matches the device on which the content is being used.
Note:In JavaScript, the rules created using@media can be accessed with theCSSMediaRule CSS object model interface.
In this article
Try it
abbr { color: #860304; font-weight: bold; transition: color 0.5s ease;}@media (hover: hover) { abbr:hover { color: #001ca8; transition-duration: 0.5s; }}@media not all and (hover: hover) { abbr::after { content: " (" attr(title) ")"; }}<p> <abbr title="National Aeronautics and Space Administration">NASA</abbr> is a U.S. government agency that is responsible for science and technology related to air and space.</p>Syntax
/* At the top level of your code */@media screen and (width >= 900px) { article { padding: 1rem 3rem; }}/* Nested within another conditional at-rule */@supports (display: flex) { @media screen and (width >= 900px) { article { display: flex; } }}The@media at-rule may be placed at the top level of your code or nested inside any other conditional group at-rule.
For a discussion of media query syntax, please seeUsing media queries.
Description
A media query's<media-query-list> includes<media-type>s,<media-feature>s, andlogical operators.
Media types
A<media-type> describes the general category of a device.Except when using theonly logical operator, the media type is optional and theall type is implied.
allSuitable for all devices.
printIntended for paged material and documents viewed on a screen in print preview mode. (Please seepaged media for information about formatting issues that are specific to these formats.)
screenIntended primarily for screens.
Note:CSS2.1 andMedia Queries 3 defined several additional media types (tty,tv,projection,handheld,braille,embossed, andaural, but they were deprecated inMedia Queries 4 and shouldn't be used.
Media features
A<media feature> describes specific characteristics of theuser agent, output device, or environment.Media feature expressions test for their presence, value, or range of values, and are entirely optional. Each media feature expression must be surrounded by parentheses.
any-hoverDoes any available input mechanism allow the user to hover over elements?
any-pointerIs any available input mechanism a pointing device, and if so, how accurate is it?
aspect-ratioWidth-to-heightaspect ratio of the viewport.
colorNumber of bits per color component of the output device, or zero if the device isn't color.
color-gamutApproximate range of colors that are supported by the user agent and output device.
color-indexNumber of entries in the output device's color lookup table, or zero if the device does not use such a table.
device-aspect-ratioWidth-to-height aspect ratio of the output device. Deprecated in Media Queries Level 4.
device-heightHeight of the rendering surface of the output device. Deprecated in Media Queries Level 4.
device-postureDetects the device's current posture, that is, whether the viewport is in a flat or folded state. Defined in theDevice Posture API.
device-widthWidth of the rendering surface of the output device. Deprecated in Media Queries Level 4.
display-modeThe mode in which an application is being displayed: for example,fullscreen orpicture-in-picture mode.Added in Media Queries Level 5.
dynamic-rangeCombination of brightness, contrast ratio, and color depth that are supported by the user agent and the output device. Added in Media Queries Level 5.
forced-colorsDetect whether user agent restricts color palette.Added in Media Queries Level 5.
gridDoes the device use a grid or bitmap screen?
heightHeight of the viewport.
horizontal-viewport-segmentsDetects whether the device has a specified number of viewport segments laid out horizontally.
hoverDoes the primary input mechanism allow the user to hover over elements?
inverted-colorsIs the user agent or underlying OS inverting colors?Added in Media Queries Level 5.
monochromeBits per pixel in the output device's monochrome frame buffer, or zero if the device isn't monochrome.
orientationOrientation of the viewport.
overflow-blockHow does the output device handle content that overflows the viewport along the block axis?
overflow-inlineCan content that overflows the viewport along the inline axis be scrolled?
pointerIs the primary input mechanism a pointing device, and if so, how accurate is it?
prefers-color-schemeDetect if the user prefers a light or dark color scheme.Added in Media Queries Level 5.
prefers-contrastDetects if the user has requested the system increase or decrease the amount of contrast between adjacent colors.Added in Media Queries Level 5.
prefers-reduced-dataDetects if the user has requested the web content that consumes less internet traffic.
prefers-reduced-motionThe user prefers less motion on the page.Added in Media Queries Level 5.
prefers-reduced-transparencyDetects if a user has enabled a setting on their device to reduce the transparent or translucent layer effects used on the device.
resolutionPixel density of the output device.
scanWhether display output is progressive or interlaced.
scriptingDetects whether scripting (i.e., JavaScript) is available.Added in Media Queries Level 5.
shapeDetects the shape of the device to distinguish rectangular and round displays.
updateHow frequently the output device can modify the appearance of content.
vertical-viewport-segmentsDetects whether the device has a specified number of viewport segments laid out vertically. Added in Media Queries Level 5.
video-dynamic-rangeCombination of brightness, contrast ratio, and color depth that are supported by the video plane of user agent and the output device. Added in Media Queries Level 5.
widthWidth of the viewport including width of scrollbar.
-moz-device-pixel-ratioThe number of device pixels per CSS pixel. Use the
resolutionfeature with thedppxunit instead.-webkit-animationThe browser supports
-webkitprefixed CSSanimation. Use the@supports (animation)feature query instead.-webkit-device-pixel-ratioThe number of device pixels per CSS pixel. Use the
resolutionfeature with thedppxunit instead.-webkit-transform-2dThe browser supports
-webkitprefixed 2D CSStransform. Use the@supports (transform)feature query instead.-webkit-transform-3dThe browser supports
-webkitprefixed 3D CSStransform. Use the@supports (transform)feature query instead.-webkit-transitionThe browser supports
-webkitprefixed CSStransition. Use the@supports (transition)feature query instead.
Logical operators
Thelogical operatorsnot,and,only, andor can be used to compose a complex media query.You can also combine multiple media queries into a single rule by separating them with commas.
andUsed for combining multiple media features together into a single media query, requiring each chained feature to return
truefor the query to betrue.It is also used for joining media features with media types.notUsed to negate a media query, returning
trueif the query would otherwise returnfalse.If present in a comma-separated list of queries, it will only negate the specific query to which it is applied.Note:In Level 3, the
notkeyword can't be used to negate an individual media feature expression, only an entire media query.onlyApplies a style only if an entire query matches.It is useful for preventing older browsers from applying selected styles.When not using
only, older browsers would interpret the queryscreen and (width <= 500px)asscreen, ignoring the remainder of the query, and applying its styles on all screens.If you use theonlyoperator, youmust also specify a media type.,(comma)Commas are used to combine multiple media queries into a single rule.Each query in a comma-separated list is treated separately from the othersThus, if any of the queries in a list is
true, the entire media statement returnstrue.In other words, lists behave like a logicaloroperator.orEquivalent to the
,operator. Added in Media Queries Level 4.
User agent client hints
Some media queries have correspondinguser agent client hints.These are HTTP headers that request content that is pre-optimized for the particular media requirement.They includeSec-CH-Prefers-Color-Scheme andSec-CH-Prefers-Reduced-Motion.
Formal syntax
@media =
@media<media-query-list> {<rule-list> }
Accessibility
To best accommodate people who adjust a site's text size, useems when you need a<length> for yourmedia queries.
Bothem andpx are valid units, butem works better if the user changes the browser text size.
Also consider media queries orHTTP user agent client hints to improve the user's experience.For example, the media queryprefers-reduced-motion or the equivalent HTTP headerSec-CH-Prefers-Reduced-Motion) can be used to minimize the amount of animation or motion used based on user preferences.
Security
Because media queries provide insights into the capabilities—and by extension, the features and design—of the device the user is working with, there is the potential that they could be abused to construct a"fingerprint" which identifies the device, or at least categorizes it to some degree of detail that may be undesirable to users.
Because of this potential, a browser may opt to fudge the returned values in some manner in order to prevent them from being used to precisely identify a computer. A browser might also offer additional measures in this area; for example, if Firefox's "Resist Fingerprinting" setting is enabled, many media queries report default values rather than values representing the actual device state.
Examples
>Testing for print and screen media types
@media print { body { font-size: 10pt; }}@media screen { body { font-size: 13px; }}@media screen, print { body { line-height: 1.2; }}The range syntax allows for less verbose media queries when testing for any feature accepting a range, as shown in the below examples:
@media (height > 600px) { body { line-height: 1.4; }}@media (400px <= width <= 700px) { body { line-height: 1.4; }}For more examples, please seeUsing media queries.
Specifications
| Specification |
|---|
| Media Queries Level 4> # media-descriptor-table> |
| CSS Conditional Rules Module Level 3> # at-media> |