@media - CSS: Cascading Style Sheets 编辑

The @media CSS at-rule can be used to apply part of a style sheet based on the result of one or more media 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 the CSSMediaRule CSS object model interface.

Syntax

The @media at-rule may be placed at the top level of your code or nested inside any other conditional group at-rule.

/* At the top level of your code */
@media screen and (min-width: 900px) {
  article {
    padding: 1rem 3rem;
  }
}

/* Nested within another conditional at-rule */
@supports (display: flex) {
  @media screen and (min-width: 900px) {
    article {
      display: flex;
    }
  }
}

For a discussion of media query syntax, please see Using media queries.

Description

Media types

Media types describe the general category of a device. Except when using the not or only logical operators, the media type is optional and the all type will be implied.

all
Suitable for all devices.
print
Intended for paged material and documents viewed on a screen in print preview mode. (Please see paged media for information about formatting issues that are specific to these formats.)
screen
Intended primarily for screens.
speech
Intended for speech synthesizers.
Deprecated media types: CSS2.1 and Media Queries 3 defined several additional media types (tty, tv, projection, handheld, braille, embossed, and aural), but they were deprecated in Media Queries 4 and shouldn't be used. The aural type has been replaced by speech, which is similar.

Media features

Media features describe specific characteristics of the user agent, output device, or environment. Media feature expressions test for their presence or value, and are entirely optional. Each media feature expression must be surrounded by parentheses.

NameSummaryNotes
any-hoverDoes any available input mechanism allow the user to hover over elements?Added in Media Queries Level 4.
any-pointerIs any available input mechanism a pointing device, and if so, how accurate is it?Added in Media Queries Level 4.
aspect-ratioWidth-to-height aspect 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 deviceAdded in Media Queries Level 4.
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-ratio This is an obsolete API and is no longer guaranteed to work.Width-to-height aspect ratio of the output deviceDeprecated in Media Queries Level 4.
device-height This is an obsolete API and is no longer guaranteed to work.Height of the rendering surface of the output deviceDeprecated in Media Queries Level 4.
device-width This is an obsolete API and is no longer guaranteed to work.Width of the rendering surface of the output deviceDeprecated in Media Queries Level 4.
display-modeThe display mode of the application, as specified in the web app manifest's display memberDefined in the Web App Manifest spec.
forced-colorsDetect whether user agent restricts color paletteAdded in Media Queries Level 5.
gridDoes the device use a grid or bitmap screen?
heightHeight of the viewport
hoverDoes the primary input mechanism allow the user to hover over elements?Added in Media Queries Level 4.
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?Added in Media Queries Level 4.
overflow-inlineCan content that overflows the viewport along the inline axis be scrolled?Added in Media Queries Level 4.
pointerIs the primary input mechanism a pointing device, and if so, how accurate is it?Added in Media Queries Level 4.
prefers-color-schemeDetect if the user prefers a light or dark color schemeAdded in Media Queries Level 5.
prefers-contrastDetects if the user has requested the system increase or decrease the amount of contrast between adjacent colorsAdded in Media Queries Level 5.
prefers-reduced-motionThe user prefers less motion on the pageAdded in Media Queries Level 5.
prefers-reduced-transparencyThe user prefers reduced transparencyAdded in Media Queries Level 5.
resolutionPixel density of the output device
scanScanning process of the output device
scriptingDetects whether scripting (i.e. JavaScript) is availableAdded in Media Queries Level 5.
updateHow frequently the output device can modify the appearance of contentAdded in Media Queries Level 4.
widthWidth of the viewport including width of scrollbar

Accessibility concerns

To best accommodate people who adjust a site's text size, use ems when you need a <length> for your media queries.

Both em and px are valid units, but em works better if the user changes the browser text size.

Also consider using Level 4 media queries to improve the user's experience. For example, prefers-reduced-motion to detect if the user has requested that the system minimize the amount of animation or motion it uses.

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.

Formal syntax

@media <media-query-list> {
  <group-rule-body>
}

where
<media-query-list> = <media-query>#

where
<media-query> = <media-condition> | [ not | only ]? <media-type> [ and <media-condition-without-or> ]?

where
<media-condition> = <media-not> | <media-and> | <media-or> | <media-in-parens>
<media-type> = <ident>
<media-condition-without-or> = <media-not> | <media-and> | <media-in-parens>

where
<media-not> = not <media-in-parens>
<media-and> = <media-in-parens> [ and <media-in-parens> ]+
<media-or> = <media-in-parens> [ or <media-in-parens> ]+
<media-in-parens> = ( <media-condition> ) | <media-feature> | <general-enclosed>

where
<media-feature> = ( [ <mf-plain> | <mf-boolean> | <mf-range> ] )
<general-enclosed> = [ <function-token> <any-value> ) ] | ( <ident> <any-value> )

where
<mf-plain> = <mf-name> : <mf-value>
<mf-boolean> = <mf-name>
<mf-range> = <mf-name> [ '<' | '>' ]? '='? <mf-value> | <mf-value> [ '<' | '>' ]? '='? <mf-name> | <mf-value> '<' '='? <mf-name> '<' '='? <mf-value> | <mf-value> '>' '='? <mf-name> '>' '='? <mf-value>

where
<mf-name> = <ident>
<mf-value> = <number> | <dimension> | <ident> | <ratio>

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; }
}

@media only screen
  and (min-width: 320px)
  and (max-width: 480px)
  and (resolution: 150dpi) {
    body { line-height: 1.4; }
}

Introduced in Media Queries Level 4 is a new range syntax that 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 see Using media queries.

Specifications

SpecificationCommentFeedback
Media Queries Level 5
The definition of '@media descriptors' in that specification.
Reinstates inverted-colors and Custom Media Queries, which were removed from Level 4.
Adds prefers-reduced-motion, prefers-reduced-transparency, prefers-contrast, and prefers-color-scheme media features.
CSS Working Group drafts GitHub issues
CSS Conditional Rules Module Level 3
The definition of '@media' in that specification.
Defines the basic syntax of the @media rule.CSS Working Group drafts GitHub issues
Media Queries Level 4
The definition of '@media' in that specification.

Adds scripting, pointer, hover, update, overflow-block, and overflow-inline media features.
Deprecates all media types except for screen, print, speech, and all.
Makes the syntax more flexible by adding, among other things, the or keyword.

CSS Working Group drafts GitHub issues
Media Queries
The definition of '@media' in that specification.
CSS Level 2 (Revision 1)
The definition of '@media' in that specification.
Initial definition.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:166 次

字数:30478

最后编辑:8 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文