媒体查询 let you adapt your site or app depending on the presence or value of various device characteristics and parameters.
They are a key component of responsive design . For example, a media query can shrink the font size on small devices, increase the padding between paragraphs when a page is viewed in portrait mode, or bump up the size of buttons on touchscreens.
在
CSS
, use the
@media
at-rule
to conditionally apply part of a style sheet based on the result of a media query. Use
@import
to conditionally apply an entire style sheet.
在 HTML , media queries can be applied to various elements:
<link>
element's
media
attribute, they define the media to which a linked resource (typically CSS) should be applied.
<source>
element's
media
attribute, they define the media to which that source should be applied. (This is only valid inside
<picture>
elements.)
<style>
element's
media
attribute, they define the media to which the style should be applied.
在
JavaScript
, you can use the
Window.matchMedia()
method to test the window against a media query. You can also use
MediaQueryList.addListener()
to be notified whenever the state of a query 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 .
Introduces media queries, their syntax, and the operators and media features which are used to construct media query expressions.
Describes how to use media queries in your JavaScript code to determine the state of a device, and to set up listeners that notify your code when the results of media queries change (such as when the user rotates the screen or resizes the browser).
Learn how Media Queries can help users understand your website better.
| 规范 | 状态 | 注释 |
|---|---|---|
| Media Queries Level 5 | 编者草案 | |
| CSS Conditional Rules Module Level 3 | 候选推荐 | |
| Media Queries Level 4 | 候选推荐 | |
| Media Queries | 推荐 | |
| CSS Level 2 (Revision 1) | 推荐 | 初始定义 |
@supports
to apply styles that depend on browser support for various CSS technologies.