@media

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

* Some parts of this feature may have varying levels of support.

Описание

CSS @-правило @media может быть использовано для применения части стилей при соблюдении условия одного или нескольких медиавыражений.

Примечание: В JavaScript правила, созданные с помощью @media могут быть получены через интерфейс объектной модели CSS CSSMediaRule.

Синтаксис

@-правило @media можно разместить на верхнем уровне CSS или внутри любого фрагмента условной группы @-правил.

css
/* На верхнем уровне кода */
@media screen and (min-width: 900px) {
  article {
    padding: 1rem 3rem;
  }
}

/* Вложено в другое условное @-правило */
@supports (display: flex) {
  @media screen and (min-width: 900px) {
    article {
      display: flex;
    }
  }
}

Для рассмотрения синтаксиса медиавыражений, см. Использование медиавыражений.

Формальный синтаксис

@media = 
@media <media-query-list> { <rule-list> }

A <media-query> is composed of a optional media type and/or a number of media features.

Типы

all

Подходит для всех устройств.

print

Intended for paged material and for documents viewed on screen in print preview mode. Please consult the section on paged media, and the media section of the Getting Started tutorial for information about formatting issues that are specific to paged media.

screen

Предназначен в первую очередь для цветных компьютерных экранов.

speech

Предназначен для синтезаторов речи.

Примечание: CSS2.1 и Media Queries 3 определили несколько дополнительных значений (tty, tv, projection, handheld, braille, embossed, aural), но они устарели в Media Queries 4 и не рекомендуется к использованию.

Media Features

Each media feature tests for one specific feature of the browser or device.

Имя Summary Notes
width Viewport width
height Viewport height
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 Is the device a grid or bitmap?
update-frequency How quickly (if at all) can the output device modify the appearance of the 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-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 0 if the device is not monochrome.
inverted-colors Is the user agent or underlying OS inverting colors? Added in Media Queries Level 4
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 Current ambient light level Added in Media Queries Level 4
scripting Is scripting (e.g. JavaScript) available? Added in Media Queries Level 4
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
-webkit-device-pixel-ratio Не стандартно Number of physical device pixels per CSS pixel Nonstandard; WebKit/Blink-specific. If possible, use the resolution media feature instead.
-webkit-transform-3d Не стандартно Are CSS 3D transforms supported? Nonstandard; WebKit/Blink-specific
-webkit-transform-2d Не стандартно Are CSS 2D transforms supported? Nonstandard; WebKit-specific
-webkit-transition Не стандартно Are CSS transitions supported? Nonstandard; WebKit-specific
-webkit-animation Не стандартно Are CSS animations supported? Nonstandard; WebKit-specific

Примеры

css
@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-device-width: 320px) and (max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2) {
  body {
    line-height: 1.4;
  }
}

Спецификации

Specification
Media Queries Level 4
# media-descriptor-table
CSS Conditional Rules Module Level 3
# at-media

Совместимость с браузерами

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
@media
-moz-device-pixel-ratio media feature
DeprecatedNon-standard
-webkit-animation media feature
DeprecatedNon-standard
-webkit-device-pixel-ratio media feature
-webkit-max-device-pixel-ratio media feature
-webkit-min-device-pixel-ratio media feature
-webkit-transform-2d media feature
Non-standard
-webkit-transform-3d media feature
-webkit-transition media feature
DeprecatedNon-standard
any-hover media feature
any-pointer media feature
aspect-ratio media feature
calc() expressions
color media feature
color-gamut media feature
color-index media feature
device-aspect-ratio media feature
Deprecated
device-height media feature
Deprecated
device-posture media feature
Experimental
device-width media feature
Deprecated
display-mode media feature
picture-in-picture value
Experimental
dynamic-range media feature
forced-colors media feature
grid media feature
height media feature
hover media feature
inverted-colors media feature
Media feature expressions
Media query value support
monochrome media feature
Nested media queries
or syntax from Media Queries Level 4
orientation media feature
overflow-block media feature
overflow-inline media feature
pointer media feature
prefers-color-scheme media feature
no-preference value
DeprecatedNon-standard
Respects color-scheme inherited from parent
Non-standard
prefers-contrast media feature
prefers-reduced-data media feature
Experimental
prefers-reduced-motion media feature
prefers-reduced-transparency media feature
Experimental
Range syntax from Media Queries Level 4
resolution media feature
scripting media feature
update media feature
video-dynamic-range media feature
width media feature

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
In development. Supported in a pre-release version.
In development. Supported in a pre-release version.
No support
No support
Experimental. Expect behavior to change in the future.
Non-standard. Check cross-browser support before using.
Deprecated. Not for use in new websites.
See implementation notes.
User must explicitly enable this feature.
Has more compatibility info.

Смотрите также