CSS - Медиа запросы (media queries). CSS - Медиа запросы (media queries) Медиа запрос в html коде

В предыдущей статье я рассказал о том, и для чего она нужна. И там я сказал, что основной механизм адаптивной вёрстки - это медиа-запросы . Вот о медиа-запросах в CSS мы и поговорим в этот раз.

Давайте сразу разберём пример медиа-запроса :


body {
font-size: 9pt;
}
}

Данный код означает следующее: "Если ширина окна браузера 768px, то применить стили, указанные в фигурных скобках ". Чтобы лучше понять, как это работает, напишите вот такой код:




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

body {
font-size: 15pt;
}
@media screen and (max-width: 768px) {
body {
font-size: 9pt;
}
}




Откройте этот код в браузере и обратите внимание на размер текста. Теперь начните уменьшать ширину окна браузера, и когда она достигнет 768px , то текст заметно уменьшится. Вот это и есть адаптивная вёрстка и работа медиа-запросов в CSS .

Безусловно, таких медиа-запросов может быть очень много, а внутри них может быть далеко не один селектор body , а сколько угодно самых разных селекторов.

Так же есть и другие параметры, такие как min-width , который будет срабатывать при указанной ширине и больше. Аналогичные параметры max-height и min-height , отвечающие за высоту. Так же можно комбинировать разные параметры через and :

@media screen and (max-width: 768px) and (max-height: 300px) {
body {
font-size: 9pt;
}
}

В данном случае стили будут подключаться только при ширине меньше, либо равной 768px и при высоте меньше, либо равной 300px .

Что касается практики, то могу смело сказать, что в 95% случаях используется лишь один max-width . Иногда ещё и min-width . И ещё раз повторяю, что есть и другие медиа-запросы в CSS , но забивать ими Вашу голову не буду. Но если очень хочется, то их можно посмотреть в справочнике.

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 with the media= attribute.
  • 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
any-hover Does any available input mechanism allow the user to hover over elements?
any-pointer Is any available input mechanism a pointing device, and if so, how accurate is it? Added in Media Queries Level 4.
aspect-ratio Width-to-height aspect ratio of the viewport
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
device-aspect-ratio Width-to-height aspect ratio of the output device
device-height Height of the rendering surface of the output device Deprecated in Media Queries Level 4.
device-width Width of the rendering surface of the output device Deprecated in 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
grid Does the device use a grid or bitmap screen?
height Height of the viewport
hover Does the primary input mechanism allow the user to hover over elements? Added in Media Queries Level 4.
inverted-colors Is the user agent or underlying OS inverting colors? Added in Media Queries Level 5.
light-level Light level of the environment Added in Media Queries Level 5.
monochrome Bits per pixel in the output device"s monochrome frame buffer, or zero if the device isn"t monochrome
orientation Orientation of the viewport
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.
pointer Is the primary input mechanism a pointing device, and if so, how accurate is it? Added in Media Queries Level 4.
prefers-color-scheme Detect if the user prefers a light or dark color scheme 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-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.
resolution Pixel density of the output device
scan Scanning process of the output device
scripting Detects whether scripting (i.e. JavaScript) is available Added in Media Queries Level 5.
update How frequently the output device can modify the appearance of content Added in Media Queries Level 4.
width Width of the viewport including width of scrollbar
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. 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 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

Медиа запросы предназначены для создания адаптивных дизайнов сайтов. Адаптивный дизайн отличается от других тем, что он может "приспосабливаться" (видоизменяться) в зависимости от того, какую ширину экрана имеет устройство (браузер). Более подробно познакомиться с адаптивным дизайном можно в статье "Что такое адаптивная разметка" .

Но при создании адаптивных веб-страниц также необходимо обратить внимание на метатег viewport. Данный тег обеспечивает корректное отображение дизайнов адаптивных сайтов на экранах устройств, имеющих высокую плотность пикселей. Иными словами, он устанавливает соответствие между CSS и физическим разрешением веб-страницы. Более подробно разобраться, как работает метатег viewport можно в статье "Знакомство с meta viewport" .

Подключение метатега viewport к странице в большинстве случаях осуществляется так:

Синтаксис медиа запросов

Для создания медиа запросов используется следующий синтаксис:

@media условие { /* стили (они будут выполняться, если устройство соответствует указанному условию) }

Основные типы устройств:

  • all - все устройства (по умолчанию).
  • print - принтеры и режим предварительного просмотра страницы перед печатью.
  • screen - устройства с дисплеями.

Логические операторы:

  • and - требует обязательного выполнения всех указанных условий.
    Например: @media screen and (min-width: 1200px) and (orientation: landscape) { /* Стили CSS ... */ } Стили CSS в вышеприведённом примере выполняться только в том случае, если страница будет выводиться на устройство с экраном, иметь область просмотра более 1200 пикселей в ширину, а также находиться в альбомном режиме.
  • , (запятая) - требует обязательного выполнения хотя бы одного из указанных условий в медиа запросе. @media (min-width: 544px), (orientation: landscape) { /* Стили CSS ... */ } Стили CSS в этом примере будут применяться к странице в двух случаях. Т.е. тогда, когда устройство будет иметь viewport не менее 544 пикселей (включительно) или ориентацию landscape.
  • not - предназначен для отрицания указанного условия. Имеет по отношению к оператору and меньший приоритет, т.е. оператор not всегда выполняется после and . @media not screen and (orientation: portrait), (min-width: 992px) { /* Стили CSS ... */ } Стили CSS, находящиеся в этом правиле, будут применены к странице только в том случае, если устройство не является screen и не будет иметь портретную ориентацию. А также они (стили CSS) будут применены к элементам документа ещё тогда, когда устройство (браузер) будет иметь ширину рабочей области не менее 992 пикселя (включительно).
    Т.е. запрос в вышеприведённом примере будет обрабатываться так: @media not (screen and (orientation: portrait)), (min-width: 992px) { /* Стили CSS ... */ }
Медиа функции

Для составления условия в @media можно использовать следующие фукнции:

  • width - указывает требования к ширине области просмотра устройства (браузера). /* применить стили CSS только для устройств с шириной области просмотра, равной 320px */ @media (width: 320px) { /* Стили CSS ... */ }
  • min-width - задаёт минимальную ширину области viewport в px , em или других единицах. /* для устройств (браузеров), которые предоставляют для страницы минимальную ширину области просмотра, равную 544 пикселя */ @media (min-width: 544px) { /* Стили CSS ... */ }
  • max-width - указывает на то, какой должна быть максимальная рабочая область устройства (браузера). /* стили, которые будут применены к элементам страницы с рабочей областью не больше 1199 пикселей */ @media (max-width: 1199px) { /* Стили CSS ... */ }
  • height , min-height и max-height - задают требования аналогично вышеприведённым функциям, но в отношении высоты viewport. /* стили, которые будут применены к элементам страницы в том случае, если viewport браузера будет больше 720px в высоту */ @media (min-height: 720px) { /* Стили CSS ... */ }
  • orientation - функция, которая проверяет то, в каком режиме (portrait или landscape) отображается страница.
    Пример, в котором в зависимости от ориентации экрана, отображается одна или другая картинка: /* landscape (альбомный) - это режим, в котором наоборот ширина viewport больше её высоты */ @media (orientation: landscape) { #background-image { background: url(image1.png) no-repeat; } } /* portrait (портретный) - это режим, в котором высота viewport больше ширины */ @media (orientation: portrait) { #background-image { background: url(image2.png) no-repeat; } }
  • aspect-ratio (min-aspect-ratio , max-aspect-ratio) - позволяют указать то, как ширина устройства должна относиться к высоте. В качестве значений допускается использовать только целые значения. /* для дисплеев с соотношением сторон 16/9 */ @media screen and (device-aspect-ratio: 16/9) { /* Стили CSS ... */ } /* для дисплеев с соотношением сторон 1336/768 */ @media screen and (device-aspect-ratio: 1336/768) { /* Стили CSS ... */ }
  • resolution (min-resolution , max-resolution) - указывает разрешение (плотность пикселей) устройства вывода. В качестве единиц измерения разрешения используются следующие величины: dpi (количество точек на дюйм), dpcm (количество точек на сантиметр), dppx (количество точек на пиксель). /* для экранов, имеющих высокую плотность пикселей (т.е. для таких, у которых отношение аппаратных пикселей к CSS не менее 2) */ @media screen and (min-resolution: 2dppx) { /* Стили CSS ... */ } /* при печати с разрешением свыше 300 точек на дюйм */ @media print and (min-resolution: 300dpi) { /* Стили CSS ... */ }
Использование медиа-запросов при подключении файлов CSS

Медиа запросы также можно применять в качестве значения атрибута media элемента link . Это позволит в зависимости от параметров устройства определить, какие файлы CSS необходимо подсоединить к странице, а какие нет. Обычно данный функционал используется тогда, когда к разным классам устройств необходимо применить различные стили CSS.

Кроме этого медиа запросы можно также использовать в правиле @import , которое предназначено для импортирования стилей из других файлов CSS в текущий.

/* импортирование стилей из файла styles-xs.css в текущий файл стилей только для устройств, которые предоставляют веб-странице viewport, имеющий ширину 543 пикселя или меньше. */ @import url(styles-xs.css) (max-width: 543px);

Медиа запросы для Bootstrap 3

Организация media queries в порядке возрастания классов устройств xs, sm, md и lg (по умолчанию):

/* Устройства с очень маленьким экраном (смартфоны, меньше 768px) */ /* Стили CSS (по умолчанию) - для ширины viewport 1200px */ }

Вышеприведённые запросы необходимо использовать только в указанном порядке.

Для того чтобы media запросы можно было применять в какой угодной последовательности, их необходимо расширить включив в них дополнительно выражение max-width . Это заставит их работать только в указанном диапазоне.

@media (max-width: 767px) { /* стили для xs-устройств */ } @media (min-width: 768px) and (max-width: 991px) { /* стили для sm-устройств */ } @media (min-width: 991px) and (max-width: 1199px) { /* стили для md-устройств */ } @media (min-width: 1200px) { /* стили для lg-устройств */ }

Медиа запросы для Bootstrap 4

Синтаксис медиа-запросов для Bootstrap 4, которые можно использовать только в следующем порядке (последовательного увеличения минимальной ширины viewport):

/* xs - устройства (до 576px) */ /* CSS для ширины, которая меньше 575px (включительно) */ /* sm-устройства (больше или равно 576px) */ @media (min-width: 576px) { /* CSS для: 576px = 1200px */ }

Список media запросов для фреймворка Bootstrap 4, которые можно применять только в обратном порядке (в порядке убывания ширины области просмотра окна браузера):

/* xl-размер (>=1200px) */ /* CSS для >=1200px */ /* lg-размер (