Media queries are a key component of responsive design, which make it possible for CSS to adapt based on various parameters or device characteristics. For example, a media query can apply different styles if the screen is smaller than a certain size, or based on whether the user is holding their device in portrait or landscape mode. The @media
at-rule is used to conditionally apply styles to a document.
In addition, the media query syntax is also used in other contexts, such as in the <source>
element's media
attribute, which can be set to a media query string to use to determine whether or not to use that source when selecting the specific image to use in a <picture>
element.
In addition, the Window.matchMedia()
method can be used to test the window against a media query. You can also use MediaQueryList.addListener()
to be notified whenever the state of the queries changes. With this functionality, your site or app can respond to changes in the device configuration, orientation, or state.
You can learn more about programmatically using media queries in Testing media queries.
Reference
At-rules
Guides
- Using media queries
- Introduces media queries, their syntax, and the operators and media features which are used to construct media query expressions.
- Testing media queries
- Describes how to test media queries from your JavaScript code, programmatically, to determine the state of the device, and to set up listeners that let your code be notified when the results of media queries change (such as when the user rotates the screen, causing an orientation change).
Specifications
Specification | Status | Comment |
---|---|---|
CSS Conditional Rules Module Level 3 | Candidate Recommendation | |
Media Queries Level 4 | Working Draft | |
Media Queries | Recommendation | |
CSS Level 2 (Revision 1) | Recommendation | Initial definition |
Browser compatibility
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 1.0 | (Yes) | 1.0 (1.7 or earlier) | 9.0 | 9.2 | 1.3 |
Feature | Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | 1.0 | (Yes) | 1.0 (1.7) | 9.0 | 9.0 | 3.1 |