使用媒体查询

翻译不完整。 请帮助我们翻译这篇文章!

媒体查询Media queries)非常实用,尤其是当你想要根据设备的大致类型(如打印设备与带屏幕的设备)或者特定的特征和设备参数(例如屏幕分辨率和浏览器视窗宽度)来修改网站或应用程序时。

媒体查询常被用于以下目的:

注意: The examples on this page use CSS's @media for illustrative purposes, but the basic syntax remains the same for all types of media queries.

语法

每条媒体查询语句都由一个可选的媒体类型和任意数量的媒体特性表达式构成。可以使用多种逻辑操作符合并多条媒体查询语句。媒体查询语句不区分大小写。

A media query computes to true when the media type (if specified) matches the device on which a document is being displayed and all media feature expressions compute as true. Queries involving unknown media types are always false.

注意: A style sheet with a media query attached to its <link> tag will still download even if the query returns false. Nevertheless, its contents will not apply unless and until the result of the query changes to true.

媒体类型

媒体类型Media types)描述设备的一般类别。除非使用 notonly 逻辑操作符,媒体类型是可选的,并且会(隐式地)应用 all 类型。

all
适用于所有设备。
print
>用于在打印预览模式下,在屏幕上查看的、分页的材料和文档。(若要了解更多有关特定于这些格式下的格式问题的信息,请参阅分页媒体。)
screen
主要用于屏幕。
speech
主要用于语音合成器。
被废弃的媒体类型: 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)描述了 user agent、输出设备,或是浏览环境的具体特征。媒体特性表达式是完全可选的,它负责测试这些特性或特征是否存在、值为多少。每条媒体特性表达式都必须用括号括起来。

名称 简介 备注
any-hover 是否有任何可用的输入机制允许用户(将鼠标等)悬停在元素上? 在 Media Queries Level 4 中被添加。
any-pointer 可用的输入机制中是否有任何指针设备,如果有,它的精度如何? 在 Media Queries Level 4 中被添加。
aspect-ratio 视窗(viewport)的宽高比
color 输出设备每个像素的比特值,常见的有 8、16、32 位。如果设备不支持输出彩色,则该值为 0
color-gamut 用户代理和输出设备大致程度上(原文:approximate)支持的色域 在 Media Queries Level 4 中被添加。
color-index 输出设备的颜色查询表(color lookup table)中的条目数量,如果设备不使用颜色查询表,则该值为 0
device-aspect-ratio 输出设备的宽高比 已在 Media Queries Level 4 中被弃用。
device-height 输出设备渲染表面(如屏幕)的高度 已在 Media Queries Level 4 中被弃用。
device-width 输出设备渲染表面(如屏幕)的宽度 已在 Media Queries Level 4 中被弃用。
display-mode The display mode of the application, as specified in the web app manifest's display member Defined in the Web App Manifest spec.
forced-colors Detect whether user agent restricts color pallete 在 Media Queries Level 5 中被添加。
grid 输出设备使用网格屏幕还是点阵屏幕?
height 视窗(viewport)的高度
hover Does the primary input mechanism allow the user to hover over elements? 在 Media Queries Level 4 中被添加。
inverted-colors Is the user agent or underlying OS inverting colors? 在 Media Queries Level 5 中被添加。
light-level 环境光亮度 在 Media Queries Level 5 中被添加。
monochrome 输出设备单色帧缓冲区中每个像素的位深度。如果设备并非黑白屏幕,则该值为 0
orientation 视窗(viewport)的旋转方向
overflow-block How does the output device handle content that overflows the viewport along the block axis? 在 Media Queries Level 4 中被添加。
overflow-inline Can content that overflows the viewport along the inline axis be scrolled? 在 Media Queries Level 4 中被添加。
pointer Is the primary input mechanism a pointing device, and if so, how accurate is it? 在 Media Queries Level 4 中被添加。
prefers-color-scheme 探测用户是否倾向于选择亮色或者暗色的配色方案 在 Media Queries Level 5 中被添加。
prefers-contrast 探测用户是否有向系统要求提高或降低相近颜色之间的对比度 在 Media Queries Level 5 中被添加。
prefers-reduced-motion 用户是否希望页面上出现更少的动态效果 在 Media Queries Level 5 中被添加。
prefers-reduced-transparency 用户是否倾向于选择更低的透明度 在 Media Queries Level 5 中被添加。
resolution 输出设备的像素密度(分辨率)
scan 输出设备的扫描过程(适用于电视等)
scripting 探测脚本(例如 JavaScript)是否可用 在 Media Queries Level 5 中被添加。
update 输出设备更新内容的渲染结果的频率 在 Media Queries Level 4 中被添加。
width 视窗(viewport)的宽度,包括纵向滚动条的宽度

逻辑操作符

逻辑操作符logical operatorsnot, and, and only 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.

and

The and operator is used for combining multiple media features together into a single media query, requiring each chained feature to return true in order for the query to be true. It is also used for joining media features with media types.

not

The not operator is used to negate a media query, returning true if the query would otherwise return false. If present in a comma-separated list of queries, it will only negate the specific query to which it is applied. If you use the not operator, you must also specify a media type.

注意: In Level 3, the not keyword can't be used to negate an individual media feature expression, only an entire media query.

only

The only operator is used to apply a style only if an entire query matches, and is useful for preventing older browsers from applying selected styles. When not using only, older browsers would interpret the query screen and (max-width: 500px) simply as screen, ignoring the remainder of the query, and applying its styles on all screens. If you use the only operator, you must 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 others. Thus, if any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like a logical or operator.

Targeting media types

Media types describe the general category of a given device. Although websites are commonly designed with screens in mind, you may want to create styles that target special devices such as printers or audio-based screenreaders. For example, this CSS targets printers:

@media print { ... }

You can also target multiple devices. For instance, this @media rule uses two media queries to target both screen and print devices:

@media screen, print { ... }

See Media types for a list of all media types. Because they describe devices in only very broad terms, just a few are available; to target more specific attributes, use media features instead.

Targeting media features

Media features describe the specific characteristics of a given user agent, output device, or environment. For instance, you can apply specific styles to widescreen monitors, computers that use mice, or to devices that are being used in low-light conditions. This example applies styles when the user's primary input mechanism (such as a mouse) can hover over elements:

@media (hover: hover) { ... }

Many media features are range features, which means they can be prefixed with "min-" or "max-" to express "minimum condition" or "maximum condition" constraints. For example, this CSS will apply styles only if your browser's viewport width is equal to or narrower than 12450px:

@media (max-width: 12450px) { ... }

If you create a media feature query without specifying a value, the nested styles will be used as long as the feature's value is not zero (or none, in Level 4). For example, this CSS will apply to any device with a color screen:

@media (color) { ... }

If a feature doesn't apply to the device on which the browser is running, expressions involving that media feature are always false. For example, the styles nested inside the following query will never be used, because no speech-only device has a screen aspect ratio:

@media speech and (aspect-ratio: 11/5) { ... }

For more media feature examples, please see the reference page for each specific feature.

Creating complex media queries

Sometimes you may want to create a media query that depends on multiple conditions. This is where the 逻辑操作符 come in: not, and, and only. Furthermore, you can combine multiple media queries into a comma-separated list; this allows you to apply the same styles in different situations.

In the previous example, we've already seen the and operator used to group a media type with a media feature. The and operator can also combine multiple media features into a single media query. The not operator, meanwhile, negates a media query, basically reversing its normal meaning. The only operator prevents older browsers from applying the styles.

注意: In most cases, the all media type is used by default when no other type is specified. However, if you use the not or only operators, you must explicitly specify a media type.

Combining multiple types or features

The and keyword combines a media feature with a media type or other media features. This example combines two media features to restrict styles to landscape-oriented devices with a width of at least 30 ems:

@media (min-width: 30em) and (orientation: landscape) { ... }

To limit the styles to devices with a screen, you can chain the media features to the screen media type:

@media screen and (min-width: 30em) and (orientation: landscape) { ... }

Testing for multiple queries

You can use a comma-separated list to apply styles when the user's device matches any one of various media types, features, or states. For instance, the following rule will apply its styles if the user's device has either a minimum height of 680px or is a screen device in portrait mode:

@media (min-height: 680px), screen and (orientation: portrait) { ... }

Taking the above example, if the user had a printer with a page height of 800px, the media statement would return true because the first query would apply. Likewise, if the user were on a smartphone in portrait mode with a viewport height of 480px, the second query would apply and the media statement would still return true.

Inverting a query's meaning

The not keyword inverts the meaning of an entire media query. It will only negate the specific media query it is applied to. (Thus, it will not apply to every media query in a comma-separated list of media queries.) The not keyword can't be used to negate an individual feature query, only an entire media query. The not is evaluated last in the following query:

@media not all and (monochrome) { ... }

... so that the above query is evaluated like this:

@media not (all and (monochrome)) { ... }

... rather than like this:

@media (not all) and (monochrome) { ... }

As another example, the following media query:

@media not screen and (color), print and (color) { ... }

... is evaluated like this:

@media (not (screen and (color))), print and (color) { ... }

Improving compatibility with older browsers

The only keyword prevents older browsers that do not support media queries with media features from applying the given styles. It has no effect on modern browsers.

@media only screen and (color) { ... }

版本 4 中的语法改进

The Media Queries Level 4 specification includes some syntax improvements to make media queries using features that have a "range" type, for example width or height, less verbose. Level 4 adds a range context for writing such queries. For example, using the max- functionality for width we might write the following:

@media (max-width: 30em) { ... }

In Media Queries Level 4 this can be written as:

@media (width <= 30em) { ... }

Using min- and max- we might test for a width between two values like so:

@media (min-width: 30em) and (max-width: 50em) { ... }

This would convert to the Level 4 syntax as:

@media (30em <= width <= 50em ) { ... }

Media Queries Level 4 also adds ways to combine media queries using full boolean algebra with and, not, and or.

Negating a feature with not

Using not() around a media feature negates that feature in the query. For example, not(hover) would match if the device had no hover capability:

@media (not(hover)) { ... }

Testing for multiple features with or

You can use or to test for a match among more than one feature, resolving to true if any of the features are true. For example, the following query tests for devices that have a monochrome display or hover capability:

@media (not (color)) or (hover) { ... }

参见