Медиа-запросы в CSS. Адаптивный и мобильный дизайн с CSS3 Media Queries

Media queries are useful when you want to modify your site or app depending on a device"s general type (such as print vs. screen) or specific characteristics and parameters (such as screen resolution or browser viewport width).

Media queries are used for the following:

  • To conditionally apply styles with the CSS @media and @import at-rules.
  • To target specific media for the , and other HTML elements.
  • To test and monitor media states using the Window.matchMedia() and MediaQueryList.addListener() JavaScript methods.

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.

Syntax

A media query is composed of an optional media type and any number of media feature expressions. Multiple queries can be combined in various ways by using logical operators . Media queries are case-insensitive.

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.

Note: A style sheet with a media query attached to its 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 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.

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
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?
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.
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
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

The logical operators not , 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.

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. 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 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 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 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 CSSСбрасываем HTML5 элементы в block Следующий CSS сделает HTML5 элементы (article, aside, figure, header, footer, etc.) блочными.
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display : block ;
} Описываем основную структуру в CSS Я снова не буду вдаваться в подробности. Основной контейнер «pagewrap» имеет ширину 980px. «Header» имеет фиксированную высоту 160px. Контейнер «content» шириной 600px и прижат влево. «Sidebar» шириной 280px и прижат вправо.
#pagewrap {
width : 980px ;
margin : 0 auto ;
}
#header {
height : 160px ;
}
#content {
width : 600px ;
float : left ;
}
#sidebar {
width : 280px ;
float : right ;
}
#footer {
clear : both ;
} Шаг 1 На первом шаге в демо не реализованы media queries, поэтому при изменении размера окна браузера, макет будет оставаться фиксированной ширины.CSS3 Media Queries Теперь начинается самое интересное – media queries .Подключаем Media Queries Javascript Internet Explorer 8 и более ранних версий не поддерживает CSS3 media queries. Вы можете включить ее, добавив Javascript файл css3-mediaqueries.js .


Подключаем CSS media queries Создаем новый CSS файл для media queries. Посмотрите мою прошлую статью, что бы увидеть как работают media queries .
Размер экрана меньше 980px (резиновый макет) Для размера экрана меньше 980px применим следующие правила:

  • pagewrap = ширина 95%;
  • content = ширина 60%;
  • sidebar = ширина 30%.
Совет: используйте проценты (%), чтобы сделать блоки резиновыми.
@media screen and (max-width: 980px) {
#pagewrap {
width : 95 % ;
}
#content {
width : 60 % ;
padding : 3 % 4 % ;
}
#sidebar {
width : 30 % ;
}
#sidebar .widget {
padding : 8 % 7 % ;
margin-bottom : 10px ;
}
}
Размер экрана меньше 650px (одноколоночный макет) Затем, задаем CSS правила для размера экрана меньше 650px.
  • header = сбрасываем высоту в auto;
  • searchform = позиционируем - 5px сверху;
  • main-nav = сбрасываем позиционирование в static;
  • site-logo = сбрасываем позиционирование в static;
  • site-description = сбрасываем позиционирование в static;
  • content = устанавливаем ширину auto (это растянет контейнер на всю ширину)
  • sidebar = устанавливаем ширину 100% и убираем float.
@media screen and (max-width: 650px) {
#header {
height : auto ;
}
#searchform {
position : absolute ;
top : 5px ;
right : 0 ;
}
#main-nav {
position : static ;
}
#site-logo {
margin : 15px 100px 5px 0 ;
position : static ;
}
#site-description {
margin : 0 0 15px ;
position : static ;
}
#content {
width : auto ;
float : none ;
margin : 20px 0 ;
}
#sidebar {
width : 100 % ;
float : none ;
margin : 0 ;
}
} Размер экрана меньше 480px Этот CSS будет применяться для размеря экрана меньше 480px, которая соответствует ширине iPhone в альбомной ориентации.
  • html = отключаем регулировку размера шрифта. По умолчанию iPhone увеличивает размер шрифта, для более комфортного чтения. Вы можете это отключить добавив -webkit-text-size-adjust: none;
  • main-nav = сбрасываем размер шрифта до 90%.
@media screen and (max-width: 480px) {
html {
-webkit-text-size-adjust: none ;
}
#main-nav a {
font-size : 90 % ;
padding : 10px 8px ;
}
} Эластичные изображения Для того, чтобы сделать изображения эластичными, просто добавьте max-width:100% и height:auto . Изображения max-width:100% и height:auto работает в IE7, но не работает в IE8 (да, еще один странный баг). Для исправления нужно добавить width:auto\9 для IE8.
img {
max-width : 100 % ;
height : auto ;
width : auto \9 ; /* ie8 */
} Эластичные встраиваемые видео Для видео применяем те же правила, как для изображений. По непонятным причинам max-width:100% (для видео) не работает в Safari. Нужно использовать width: 100% .
.video embed ,
.video object,
.video iframe {
width : 100 % ;
height : auto ;
} Initial Scale Meta Tag (iPhone) По умолчанию iPhone Safari сжимает станицы, что бы вместить в экран. Следующий мета-тег говорит iPhone Safari использовать ширину устройства как ширину окна и отключить.
Финальное Демо Откроем финальное демо и поизменяем размер экрана, что бы увидеть media queries в действии. Не забудьте проверить в iPhone, iPad, Blackberry (последние версии) и Android телефонах, что бы увидеть мобильную версию.

Итак, в этом материале мы затронем весьма интересную тему создания адаптивных HTML страниц путём использования CSS медиа запросов.

Что вообще такое эти медиа запросы CSS? Эти самые запросы представляют собой обрамлённые коды в определённом синтаксисе, которые применяются только если экран пользователя соответствует условию запроса.

Вот пример запроса:

@media screen and (max-width: 600px) {
body {
background: #ccc;
}
/*Ваш код CSS*/
}

Из премера ясно что код будет применяться если экран видимая область для сайта (viewport) конечного пользователя меньше или равен 600 пикселям по ширине.

Внутри такого запроса может быть сколько угодно элементов к которым применяется сколько угодно свойств и все они будут задействованы только когда выполняется условие медиа запроса. Эта система напоминает своим принципом стандартный оператор if(){}, который имеется у большинства языков программирования. Как и в случае с if, медиа запросы могут иметь сразу несколько условий для выполнения вложенного CSS кода. Например:

@media screen and (min-width: 600px) and (max-width: 1000px) {
body {
background: #ccc;
}
/*Ваш код CSS*/
}

Сразу видно что выполняться будет если ширина вьюпорта от 600 до 1000 пикселей.

Как вы уже понились зам запрос строиться так:

@media screen and (УСЛОВИЕ){
/*Код*/
}

Вы наверное обратили внимание на слово screen. Это значит что-то вроде типа устройства куда идёт вывод. Ещё, кроме screen есть: all, projection, tv, print, 3d-glasses. Для мониторов, мобилок это screen , поэтому с ним у нас и все примеры. Вообще вместо него лучше ставить all (для всего), если вы не уверены с какого вентилятора пользователь откроет ваше приложение или игру или что там у вас.

Писать запросы вы можете как в css файлах, так и в самих HTML страницах. Более того вы можете в HTML вы можете создать медиа запросом условие при котором будет подключен файл:

Это файл который подключиться если плотность пикселей составит 2. Применяется в основном для идентификации четвёртого айфона.

Таким самым образом можно отдельно написать CSS файлы для портретной или ландшафтной ориентации:


Это применяется многими веб-девелоперами.

С этим разобрались. Давайте теперь посмотрим какие запросы вообще могут применяться и работать в современных браузерах.

CSS Медиа запросы

Теперь мы посмотрим какие медиа запросы CSS ипользуются чаще всего и возможно вам пригодятся.

Список свойств будет написан с выдуманными параметрами чтобы вы понимали какие значения может содержать то или иное свойство:

min-width:100px - Минимальная ширина окна
max-width:35em - Максимальная ширина окна
max-device-width: 480px - Максимальная ширина устройства (в пикселях)
device-width: 768px - Ширина устройства
device-aspect-ratio: 9/16 - Соотношение сторон
orientation:landscape - Ландшафтная ориентация
orientation:portrait - Портретная ориентация
resolution: 96dpi - Плотность экрана
min-resolution: 192dpi - Минимальная плотность экрана
-webkit-device-pixel-ratio: .75 - Коэффициент плотности экрана (в примере значение 0.75)
-webkit-min-device-pixel-ratio: 1.3 Минимальный коэффициент плотности экрана

О последних параметрах хочется немного поговорить. Добавлю что resolution нестабильно работает. Некоторые устройства не принимают должным образом запрос. А вот -webkit-device-pixel-ratio это собственно условный коэффициент плотности экрана 0.75 это экран с низкой плотностью пикселей, а 2 это Retina.

P.S. Если вы хотите быстро проверить какие CSS запросы работают с вашим устройством и что они собственно отдают, тогда посетите эту страницу вашим устройством.

  • Перевод

Разрешение экрана в наши дни колеблется от 320px (iPhone) до 2560px (большие мониторы) или даже выше. Пользователи больше не просматривают сайты только на настольных компьютерах. Теперь пользователи используют мобильные телефоны, небольшие ноутбуки, планшетные устройства, такие как iPad или Playbook для доступа в интернет. Поэтому, традиционный дизайн с фиксированной шириной больше не работает. Дизайн должен быть адаптивным. Структура должна автоматически изменяться с учетом всех разрешений дисплеев. Эта статья покажет вам как создавать кросс-браузерный адаптивный дизайн при помощи HTML5 и CSS3 media queries.

Для начала посмотрим это в действии. Пред началом посмотрите на финальное демо , что бы увидеть, как хорошо это выглядит. Изменяйте размер браузера, что бы увидеть как структура автоматически изменяется основываясь на ширине окна.Другие примеры Если вы хотите увидеть больше примеров, посмотрите следующие темы для WordPress , которые я сделал используя media queries: iTheme2 , Funki , Minblr и Wumblr .Обзор Контейнер страницы имеет ширину 980px для любого разрешения, больше 1024px. Для проверки ширины используются media queries, если ширина меньше чем 980px, в этом случае макет становится резиновым, вместо фиксированной ширины. Если ширина меньше 650px, то контейнеры с контентом и боковой панелью расширяются на полный экран и становятся в одну колонку.

HTML Не будем останавливаться на подробном описании HTML. Ниже описана основная структура макета. У меня есть «pagewrap», который включает в себя «header», «content», «sidebar» и «footer».



Demo
Site Description



Home








blog post



class = "widget" >
widget



footer

HTML5.js Обратите внимание, что в демо используется HTML5. Internet Explorer ниже 9-й версии не поддерживает новые элементы содержащиеся в HTML5, такие как , , , и прочие. Поэтому подключаем Javascript файл html5.js в HTML документ, который позволит IE понимать новые элементы.


CSSСбрасываем HTML5 элементы в block Следующий CSS сделает HTML5 элементы (article, aside, figure, header, footer, etc.) блочными.
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display : block ;
} Описываем основную структуру в CSS Я снова не буду вдаваться в подробности. Основной контейнер «pagewrap» имеет ширину 980px. «Header» имеет фиксированную высоту 160px. Контейнер «content» шириной 600px и прижат влево. «Sidebar» шириной 280px и прижат вправо.
#pagewrap {
width : 980px ;
margin : 0 auto ;
}
#header {
height : 160px ;
}
#content {
width : 600px ;
float : left ;
}
#sidebar {
width : 280px ;
float : right ;
}
#footer {
clear : both ;
} Шаг 1 На первом шаге в демо не реализованы media queries, поэтому при изменении размера окна браузера, макет будет оставаться фиксированной ширины.CSS3 Media Queries Теперь начинается самое интересное – media queries .Подключаем Media Queries Javascript Internet Explorer 8 и более ранних версий не поддерживает CSS3 media queries. Вы можете включить ее, добавив Javascript файл css3-mediaqueries.js .


Подключаем CSS media queries Создаем новый CSS файл для media queries. Посмотрите мою прошлую статью, что бы увидеть как работают media queries .
Размер экрана меньше 980px (резиновый макет) Для размера экрана меньше 980px применим следующие правила:
  • pagewrap = ширина 95%;
  • content = ширина 60%;
  • sidebar = ширина 30%.
Совет: используйте проценты (%), чтобы сделать блоки резиновыми.
@media screen and (max-width: 980px) {
#pagewrap {
width : 95 % ;
}
#content {
width : 60 % ;
padding : 3 % 4 % ;
}
#sidebar {
width : 30 % ;
}
#sidebar .widget {
padding : 8 % 7 % ;
margin-bottom : 10px ;
}
}
Размер экрана меньше 650px (одноколоночный макет) Затем, задаем CSS правила для размера экрана меньше 650px.
  • header = сбрасываем высоту в auto;
  • searchform = позиционируем - 5px сверху;
  • main-nav = сбрасываем позиционирование в static;
  • site-logo = сбрасываем позиционирование в static;
  • site-description = сбрасываем позиционирование в static;
  • content = устанавливаем ширину auto (это растянет контейнер на всю ширину)
  • sidebar = устанавливаем ширину 100% и убираем float.
@media screen and (max-width: 650px) {
#header {
height : auto ;
}
#searchform {
position : absolute ;
top : 5px ;
right : 0 ;
}
#main-nav {
position : static ;
}
#site-logo {
margin : 15px 100px 5px 0 ;
position : static ;
}
#site-description {
margin : 0 0 15px ;
position : static ;
}
#content {
width : auto ;
float : none ;
margin : 20px 0 ;
}
#sidebar {
width : 100 % ;
float : none ;
margin : 0 ;
}
} Размер экрана меньше 480px Этот CSS будет применяться для размеря экрана меньше 480px, которая соответствует ширине iPhone в альбомной ориентации.
  • html = отключаем регулировку размера шрифта. По умолчанию iPhone увеличивает размер шрифта, для более комфортного чтения. Вы можете это отключить добавив -webkit-text-size-adjust: none;
  • main-nav = сбрасываем размер шрифта до 90%.
@media screen and (max-width: 480px) {
html {
-webkit-text-size-adjust: none ;
}
#main-nav a {
font-size : 90 % ;
padding : 10px 8px ;
}
} Эластичные изображения Для того, чтобы сделать изображения эластичными, просто добавьте max-width:100% и height:auto . Изображения max-width:100% и height:auto работает в IE7, но не работает в IE8 (да, еще один странный баг). Для исправления нужно добавить width:auto\9 для IE8.
img {
max-width : 100 % ;
height : auto ;
width : auto \9 ; /* ie8 */
} Эластичные встраиваемые видео Для видео применяем те же правила, как для изображений. По непонятным причинам max-width:100% (для видео) не работает в Safari. Нужно использовать width: 100% .
.video embed ,
.video object,
.video iframe {
width : 100 % ;
height : auto ;
} Initial Scale Meta Tag (iPhone) По умолчанию iPhone Safari сжимает станицы, что бы вместить в экран. Следующий мета-тег говорит iPhone Safari использовать ширину устройства как ширину окна и отключить.
Финальное Демо Откроем финальное демо и поизменяем размер экрана, что бы увидеть media queries в действии. Не забудьте проверить в iPhone, iPad, Blackberry (последние версии) и Android телефонах, что бы увидеть мобильную версию.