Правило CSS @media
Пример
Измените цвет фона элемента <body> на «светло-синий», когда окно браузера имеет ширину 600 пикселей или меньше:
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
Другие примеры «Попробуйте сами» ниже.
Определение и использование
Правило @media
используется в медиа-запросах для применения разных стилей к разным типам/устройствам медиа.
Медиа-запросы можно использовать для проверки многих вещей, таких как:
- ширина и высота области просмотра
- ширина и высота устройства
- ориентация (планшет/телефон в ландшафтном или портретном режиме?)
- разрешающая способность
Использование медиа-запросов — это популярный метод доставки адаптированной таблицы стилей (адаптивного веб-дизайна) на настольные компьютеры, ноутбуки, планшеты и мобильные телефоны.
Вы также можете использовать медиа-запросы, чтобы указать, что определенные стили предназначены только для печатных документов или программ чтения с экрана (тип медиа: печать, экран или речь).
В дополнение к типам мультимедиа существуют также функции мультимедиа. Медиа-функции предоставляют более подробную информацию для медиа-запросов, позволяя тестировать определенную функцию пользовательского агента или устройства отображения. Например, вы можете применять стили только к тем экранам, которые больше или меньше определенной ширины.
Поддержка браузера
Цифры в таблице указывают на первую версию браузера, которая полностью поддерживает правило @media.
Property | |||||
---|---|---|---|---|---|
@media | 21 | 9 | 3.5 | 4.0 | 9 |
Синтаксис CSS
@media not|only mediatype and (mediafeature and|or|not
mediafeature) {
CSS-Code;
}
значение ключевых слов not , only и and :
not: Ключевое слово not инвертирует смысл всего медиа-запроса.
only: ключевое слово only не позволяет старым браузерам, которые не поддерживают медиа-запросы с медиа-функциями, применять указанные стили. Это не влияет на современные браузеры.
и: ключевое слово and объединяет функцию мультимедиа с типом мультимедиа или другими функциями мультимедиа.
Все они являются необязательными. Однако, если вы используете not или only , вы также должны указать тип носителя.
У вас также могут быть разные таблицы стилей для разных носителей, например:
<link rel="stylesheet" media="screen and (min-width:
900px)" href="widescreen.css">
<link rel="stylesheet" media="screen and (max-width:
600px)" href="smallscreen.css">
....
Типы носителей
Value | Description |
---|---|
all | Default. Used for all media type devices |
Used for printers | |
screen | Used for computer screens, tablets, smart-phones etc. |
speech | Used for screenreaders that "reads" the page out loud |
Медиа-функции
Value | Description |
---|---|
any-hover | Does any available 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) |
aspect-ratio | The ratio between the width and the height of the viewport |
color | The number of bits per color component for the output device |
color-gamut | The approximate range of colors that are supported by the user agent and output device (added in Media Queries Level 4) |
color-index | The number of colors the device can display |
grid | Whether the device is a grid or bitmap |
height | The viewport height |
hover | Does the primary input mechanism allow the user to hover over elements? (added in Media Queries Level 4) |
inverted-colors | Is the browser or underlying OS inverting colors? (added in Media Queries Level 4) |
light-level | Current ambient light level (added in Media Queries Level 4) |
max-aspect-ratio | The maximum ratio between the width and the height of the display area |
max-color | The maximum number of bits per color component for the output device |
max-color-index | The maximum number of colors the device can display |
max-height | The maximum height of the display area, such as a browser window |
max-monochrome | The maximum number of bits per "color" on a monochrome (greyscale) device |
max-resolution | The maximum resolution of the device, using dpi or dpcm |
max-width | The maximum width of the display area, such as a browser window |
min-aspect-ratio | The minimum ratio between the width and the height of the display area |
min-color | The minimum number of bits per color component for the output device |
min-color-index | The minimum number of colors the device can display |
min-height | The minimum height of the display area, such as a browser window |
min-monochrome | The minimum number of bits per "color" on a monochrome (greyscale) device |
min-resolution | The minimum resolution of the device, using dpi or dpcm |
min-width | The minimum width of the display area, such as a browser window |
monochrome | The number of bits per "color" on a monochrome (greyscale) device |
orientation | The orientation of the viewport (landscape or portrait mode) |
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) |
resolution | The resolution of the output device, using dpi or dpcm |
scan | The scanning process of the output device |
scripting | Is scripting (e.g. JavaScript) available? (added in Media Queries Level 4) |
update | How quickly can the output device modify the appearance of the content (added in Media Queries Level 4) |
width | The viewport width |
Дополнительные примеры
Пример
Скрыть элемент, если ширина браузера составляет 600 пикселей или меньше:
@media screen and (max-width: 600px) {
div.example {
display:
none;
}
}
Пример
Используйте медиазапросы, чтобы установить для фона лавандовый цвет, если окно просмотра имеет ширину 800 пикселей или шире, или светло-зеленый, если окно просмотра имеет ширину от 400 до 799 пикселей. Если область просмотра меньше 400 пикселей, цвет фона светло-синий:
body {
background-color: lightblue;
}
@media screen and (min-width:
400px) {
body {
background-color: lightgreen;
}
}
@media
screen and (min-width: 800px) {
body {
background-color: lavender;
}
}
Пример
Создайте адаптивное навигационное меню (отображаемое горизонтально на больших экранах и вертикально на маленьких экранах):
@media screen and (max-width: 600px) {
.topnav a {
float: none;
width: 100%;
}
}
Пример
Используйте медиа-запросы для создания адаптивного макета столбца:
/* 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%;
}
}
Пример
Используйте медиа-запросы для создания адаптивного веб-сайта:
Пример
Медиа-запросы также можно использовать для изменения макета страницы в зависимости от ориентации браузера. У вас может быть набор свойств CSS, которые будут применяться только тогда, когда окно браузера шире, чем его высота, так называемая "альбомная" ориентация.
Используйте светло-голубой цвет фона, если ориентация находится в ландшафтном режиме:
@media only screen and (orientation:
landscape) {
body {
background-color: lightblue;
}
}
Пример
Используйте медиазапросы, чтобы установить зеленый цвет текста, когда документ отображается на экране, и черный, когда он печатается:
@media screen {
body {
color: green;
}
}
@media print {
body {
color: black;
}
}
Пример
Список, разделенный запятыми : добавьте дополнительный медиа-запрос к уже существующему, используя запятую (это будет вести себя как оператор ИЛИ):
/* When the width is between 600px and 900px OR above 1100px - change the
appearance of <div> */
@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;
}
}
Связанные страницы
Учебник по CSS: Медиа-запросы CSS
Учебное пособие по CSS: примеры медиазапросов CSS
Учебник RWD: Адаптивный веб-дизайн с медиа-запросами
Учебник по JavaScript: метод window.matchMedia()