CSS @media Rule
Change the background color of the element to «lightblue» when the browser window is 600px wide or less:
More «Try it Yourself» examples below.
Definition and Usage
The @media rule is used in media queries to apply different styles for different media types/devices.
Media queries can be used to check many things, such as:
- width and height of the viewport
- width and height of the device
- orientation (is the tablet/phone in landscape or portrait mode?)
- resolution
Using media queries are a popular technique for delivering a tailored style sheet (responsive web design) to desktops, laptops, tablets, and mobile phones.
You can also use media queries to specify that certain styles are only for printed documents or for screen readers (mediatype: print, screen, or speech).
In addition to media types, there are also media features. Media features provide more specific details to media queries, by allowing to test for a specific feature of the user agent or display device. For example, you can apply styles to only those screens that are greater, or smaller, than a certain width.
Browser Support
The numbers in the table specifies the first browser version that fully supports the @media rule.
CSS Syntax
meaning of the not, only and and keywords:
not: The not keyword inverts the meaning of an entire media query.
only: The only keyword prevents older browsers that do not support media queries with media features from applying the specified styles. It has no effect on modern browsers.
and: The and keyword combines a media feature with a media type or other media features.
They are all optional. However, if you use not or only, you must also specify a media type.
You can also have different stylesheets for different media, like this:
More Examples
Example
Hide an element when the browser’s width is 600px wide or less:
Example
Use mediaqueries to set the background-color to lavender if the viewport is 800 pixels wide or wider, to lightgreen if the viewport is between 400 and 799 pixels wide. If the viewport is smaller than 400 pixels, the background-color is lightblue:
body <
background-color: lightblue;
>
@media screen and (min-width: 400px) body background-color: lightgreen;
>
>
@media screen and (min-width: 800px) body background-color: lavender;
>
>
Example
Create a responsive navigation menu (displayed horizontally on large screens and vertically on small screens):
Example
Use media queries to create a responsive column layout:
/* On screens that are 992px wide or less, go from four columns to two columns */
@media screen and (max-width: 992px) .column width: 50%;
>
>
/* On screens that are 600px wide or less, make the columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) .column width: 100%;
>
>
Example
Use media queries to create a responsive website:
Example
Media queries can also be used to change layout of a page depending on the orientation of the browser. You can have a set of CSS properties that will only apply when the browser window is wider than its height, a so called «Landscape» orientation.
Use a lightblue background color if the orientation is in landscape mode:
Example
Use mediaqueries to set the text color to green when the document is displayed on the screen, and to black when it is printed:
Example
Comma separated list: add an additional media query to an already existing one, using a comma (this will behave like an OR operator):
/* When the width is between 600px and 900px OR above 1100px — change the appearance of
@media screen and (max-width: 900px) and (min-width: 600px), (min-width: 1100px) div.example font-size: 50px;
padding: 50px;
border: 8px solid black;
background: yellow;
>
>
@media
At-правило @media в CSS связывает набор операторов, ограниченных фигурными скобками, в CSS блок, применяется при соблюдении условия одного или нескольких медиавыражений.
Примечание: В JavaScript, at-правило @media может быть получено с помощью CSSMediaRule (en-US), интерфейса объектной модели CSS.
Синтаксис
At-правило @media можно разместить не только на верхнем уровне CSS, но и внутри любого фрагмента условной группы-правил.
/* На верхнем уровне кода */ @media screen and (min-width: 900px) article padding: 1rem 3rem; > > /* Вложено в другое условное at-правило */ @supports (display: flex) @media screen and (min-width: 900px) article display: flex; > > >
Для рассмотрения синтаксиса медиавыражений, см. Использование медиавыражений.
Формальный синтаксис
A is composed of a optional media type and/or a number of media features.
Типы
Подходит для всех устройств.
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.
Предназначен в первую очередь для цветных компьютерных экранов.
Предназначен для синтезаторов речи.
Примечание: 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 (en-US) | Viewport width | |
height (en-US) | Viewport height | |
aspect-ratio (en-US) | Width-to-height aspect ratio of the viewport | |
orientation | Orientation of the viewport | |
resolution (en-US) | Pixel density of the output device | |
scan | Scanning process of the output device | |
grid (en-US) | Is the device a grid or bitmap? | |
update-frequency (en-US) | How quickly (if at all) can the output device modify the appearance of the content | Added in Media Queries Level 4 |
overflow-block (en-US) | How does the output device handle content that overflows the viewport along the block axis? | Added in Media Queries Level 4 |
overflow-inline (en-US) | Can content that overflows the viewport along the inline axis be scrolled? | Added in Media Queries Level 4 |
color (en-US) | Number of bits per color component of the output device, or zero if the device isn’t color. | |
color-index (en-US) | Number of entries in the output device’s color lookup table, or zero if the device does not use such a table. | |
display-mode (en-US) | The display mode of the application, as specified in the web app manifest’s display member. | Defined in the Web App Manifest spec. |
monochrome (en-US) | 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 (en-US) | Is the primary input mechanism a pointing device, and if so, how accurate is it? | Added in Media Queries Level 4 |
hover (en-US) | Does the primary input mechanism allow the user to hover over elements? | Added in Media Queries Level 4 |
any-pointer (en-US) | Is any available input mechanism a pointing device, and if so, how accurate is it? | Added in Media Queries Level 4 |
any-hover (en-US) | 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 (en-US) | Width of the rendering surface of the output device | Deprecated in Media Queries Level 4 |
device-height (en-US) | Height of the rendering surface of the output device | Deprecated in Media Queries Level 4 |
device-aspect-ratio (en-US) | Width-to-height aspect ratio of the output device | Deprecated in Media Queries Level 4 |
-webkit-device-pixel-ratio (en-US) Non-standard | Number of physical device pixels per CSS pixel | Nonstandard; WebKit/Blink-specific. If possible, use the resolution (en-US) media feature instead. |
-webkit-transform-3d (en-US) Non-standard | Are CSS 3D transform s supported? | Nonstandard; WebKit/Blink-specific |
-webkit-transform-2d (en-US) Non-standard | Are CSS 2D transform s supported? | Nonstandard; WebKit-specific |
-webkit-transition (en-US) Non-standard | Are CSS transition s supported? | Nonstandard; WebKit-specific |
-webkit-animation (en-US) Non-standard | Are CSS animation s supported? | Nonstandard; WebKit-specific |
Примеры
@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 > >
Спецификации
Совместимость с браузерами
BCD tables only load in the browser