使用 media queries

當您想要根據設備的型態(例如列印 vs. 螢幕 )或是特定特徵及參數(例如螢幕解析度或瀏覽器 viewport 寬度 )來更改網站或應用程式時,Media queries  非常有用。

Media queries 用途如下:

Note: 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.

語法

一個 media query 是由一個可選的 media types 及數量不等的 media feature 運算式組成。多個 queries 可經由 logical operators ,藉多種方式合成一個。而撰寫時,media query 是不區分大小寫的。

當  media types(如果有指定的話)與正在顯示內容的裝置相符,而且所有指定的 media feature 運算式結果也為 true 時,media query 將會被運算為 true。

使用未知 media 類型的 media query 將會永遠是 false 。

Note: 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

Media types 描述普遍的裝置類型,它是可選的,除非使用 not 是 only 邏輯運算子,不然 all 會被隱含的使用。

all
適用於所有裝備。
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
主要適用於螢幕。
speech
主要適用於語音合成器。
Deprecated media types: CSS2.1 and Media Queries 3 定義了許多新增的 media types (tty, tv, projection, handheld, braille, embossed, 及 aural), 但他們在  Media Queries 4 都被棄用了,因此不該考慮使用它們。而 aural 類型則被 speech 取代,也不該使用。

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.

Name Summary Notes
width Width of the viewport
height Height of the viewport
aspect-ratio Width-to-height aspect ratio of the viewport
orientation Orientation of the viewport
resolution Pixel density of the output device
scan Scanning process of the output device
grid Does the device use a grid or bitmap screen?
update How frequently the output device can modify the appearance of content Added in Media Queries Level 4.
overflow-block How does the output device handle content that overflows the viewport along the block axis? Added in Media Queries Level 4.
overflow-inline Can content that overflows the viewport along the inline axis be scrolled? Added in Media Queries Level 4.
color Number of bits per color component of the output device, or zero if the device isn't color
color-gamut Approximate range of colors that are supported by the user agent and output device Added in Media Queries Level 4.
color-index Number of entries in the output device's color lookup table, or zero if the device does not use such a table
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.
monochrome Bits per pixel in the output device's monochrome frame buffer, or zero if the device isn't monochrome
inverted-colors Is the user agent or underlying OS inverting colors? Added in Media Queries Level 5.
pointer Is the primary input mechanism a pointing device, and if so, how accurate is it? Added in Media Queries Level 4.
hover Does the primary input mechanism allow the user to hover over elements? Added in Media Queries Level 4.
any-pointer Is any available input mechanism a pointing device, and if so, how accurate is it? Added in Media Queries Level 4.
any-hover Does any available input mechanism allow the user to hover over elements? Added in Media Queries Level 4.
light-level Light level of the environment Added in Media Queries Level 5.
prefers-reduced-motion The user prefers less motion on the page Added in Media Queries Level 5.
prefers-reduced-transparency The user prefers reduced transparency Added in Media Queries Level 5.
prefers-contrast Detects if the user has requested the system increase or decrease the amount of contrast between adjacent colors Added in Media Queries Level 5.
prefers-color-scheme Detect if the user prefers a light or dark color scheme Added in Media Queries Level 5.
forced-colors Detect whether user agent restricts color pallete Added in Media Queries Level 5.
scripting Detects whether scripting (i.e. JavaScript) is available Added in Media Queries Level 5.
device-width Width of the rendering surface of the output device Deprecated in Media Queries Level 4.
device-height Height of the rendering surface of the output device Deprecated in Media Queries Level 4.
device-aspect-ratio Width-to-height aspect ratio of the output device Deprecated in Media Queries Level 4.

Logical operators

logical operators not, and, 及 only 可以用來合成一個複雜的 media query。你可也以用逗號將多個 media queries 合併成一個。

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.

Note: 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.

指定 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.

指定 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.

創建複雜的 media queries

Sometimes you may want to create a media query that depends on multiple conditions. This is where the logical operators 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.

Note: 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) { ... }

Syntax improvements in Level 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) { ... }

參考