Медиазапросы CSS
Адаптивные веб-страницы опираются на медиазапросы, которые применяют стили в соответствии с характеристиками устройства или среды, отображающей страницу.
Они добавляются в таблицу стилей с помощью правила CSS @media.
Использование медиазапросов для добавления точки перелома
На предыдущей странице была создана веб-страница с сеточной раскладкой. Теперь ей нужна точка перелома, чтобы медиазапрос мог перестроить её элементы сетки на больших экранах.
Пример
Медиазапрос в этом примере задаёт точку перелома при 600px:
Результат: полная HTML-страница
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add a Breakpoint</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: Arial, sans-serif; }
.grid-container {
display: grid;
grid-template-columns: 1fr;
gap: 0;
}
.header { background-color: #2196F3; color: white; padding: 15px; text-align: center; }
.menu { background-color: #33b5e5; color: white; padding: 15px; }
.content { background-color: #f1f1f1; padding: 15px; }
.facts { background-color: #ccc; padding: 15px; }
.footer { background-color: #2196F3; color: white; padding: 15px; text-align: center; }
.menu ul { list-style-type: none; padding: 0; }
.menu li { padding: 8px 0; }
@media (min-width: 600px) {
.grid-container {
grid-template-columns: repeat(6, 1fr);
}
.header { grid-column: 1 / span 6; }
.menu { grid-column: 1 / span 1; }
.content { grid-column: 2 / span 4; }
.facts { grid-column: 6 / span 1; }
.footer { grid-column: 1 / span 6; }
}
</style>
</head>
<body>
<div class="grid-container">
<div class="header"><h1>Header</h1></div>
<div class="menu">
<ul>
<li>The Flight</li>
<li>The City</li>
<li>The Island</li>
<li>The Food</li>
</ul>
</div>
<div class="content">
<h2>The City</h2>
<p>Chania is the capital of the Chania region on the island of Crete. The city can be divided in two parts, the old town and the modern city.</p>
<p>Resize the browser window to see how the content respond to the resizing.</p>
</div>
<div class="facts">
<h2>Facts</h2>
<p>Chania was founded in 1252.</p>
</div>
<div class="footer"><p>Footer</p></div>
</div>
</body>
</html>
Ещё одна точка перелома
Количество точек перелома не ограничено, поэтому добавляйте столько, сколько хотите.
Пример
Эти медиазапросы добавляют две точки перелома: одну для экранов шириной не менее 600px и одну для экранов шириной не менее 768px:
Результат: полная HTML-страница
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Another Breakpoint</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: Arial, sans-serif; }
.grid-container {
display: grid;
grid-template-columns: 1fr;
gap: 0;
}
.header { background-color: #2196F3; color: white; padding: 15px; text-align: center; }
.menu { background-color: #33b5e5; color: white; padding: 15px; }
.content { background-color: #f1f1f1; padding: 15px; }
.facts { background-color: #ccc; padding: 15px; }
.footer { background-color: #2196F3; color: white; padding: 15px; text-align: center; }
.menu ul { list-style-type: none; padding: 0; }
.menu li { padding: 8px 0; }
@media (min-width: 600px) {
.grid-container {
grid-template-columns: repeat(6, 1fr);
}
.header { grid-column: 1 / span 6; }
.menu { grid-column: 1 / span 1; }
.content { grid-column: 2 / span 4; }
.facts { grid-column: 1 / span 6; }
.footer { grid-column: 1 / span 6; }
}
@media (min-width: 768px) {
.header { grid-column: 1 / span 6; }
.menu { grid-column: 1 / span 1; }
.content { grid-column: 2 / span 4; }
.facts { grid-column: 6 / span 1; }
.footer { grid-column: 1 / span 6; }
}
</style>
</head>
<body>
<div class="grid-container">
<div class="header"><h1>Header</h1></div>
<div class="menu">
<ul>
<li>The Flight</li>
<li>The City</li>
<li>The Island</li>
<li>The Food</li>
</ul>
</div>
<div class="content">
<h2>The City</h2>
<p>Chania is the capital of the Chania region on the island of Crete. The city can be divided in two parts, the old town and the modern city.</p>
<p>Resize the browser window to see how the content respond to the resizing.</p>
</div>
<div class="facts">
<h2>Facts</h2>
<p>Chania was founded in 1252.</p>
</div>
<div class="footer"><p>Footer</p></div>
</div>
</body>
</html>
Типичные точки перелома для устройств
Экранов и устройств с разной высотой и шириной так много, что создать точную точку перелома для каждого из них сложно. Ориентация на пять распространённых групп упрощает задачу.
Пример
Результат: полная HTML-страница
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Typical Device Breakpoints</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 40px;
}
.size-label { font-size: 30px; }
/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {
body { background-color: lightcoral; }
.size-label::after { content: "Extra Small (600px and down)"; }
}
/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {
body { background-color: lightsalmon; }
.size-label::after { content: "Small (600px and up)"; }
}
/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) {
body { background-color: lightyellow; }
.size-label::after { content: "Medium (768px and up)"; }
}
/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px) {
body { background-color: lightgreen; }
.size-label::after { content: "Large (992px and up)"; }
}
/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {
body { background-color: lightblue; }
.size-label::after { content: "Extra Large (1200px and up)"; }
}
</style>
</head>
<body>
<h1>Resize the browser window to see the effect!</h1>
<p class="size-label"></p>
</body>
</html>
Медиазапросы для ориентации экрана
Раскладка страницы также может реагировать на ориентацию экрана с помощью медиазапросов.
В альбомном режиме в этом примере меняется цвет фона body:
Пример
Результат: полная HTML-страница
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Orientation Media Query</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
@media only screen and (orientation: landscape) {
body {
background-color: lightblue;
}
}
</style>
</head>
<body>
<p>Resize the browser window. When the width is greater than the height (landscape mode), the background color will be lightblue.</p>
</body>
</html>
Скрытие элементов с помощью медиазапросов
На маленьких экранах медиазапрос ниже скрывает элемент:
Пример
Результат: полная HTML-страница
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hide Elements With Media Queries</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
#div1 {
background-color: lightgreen;
padding: 20px;
font-size: 24px;
}
/* Hide element if the viewport width is 600px or less */
@media screen and (max-width: 600px) {
#div1 {
display: none;
}
}
</style>
</head>
<body>
<div id="div1">I will be hidden on small screens.</div>
<p>Resize the browser window to hide the green box when the width is 600px or less.</p>
</body>
</html>
Изменение размера шрифта с помощью медиазапросов
По мере изменения ширины области просмотра медиазапрос ниже изменяет размер шрифта элемента:
Пример
Результат: полная HTML-страница
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Font Size With Media Queries</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
#div1 {
background-color: lightblue;
padding: 20px;
}
/* If viewport width is 600px or more, set font-size to 80px */
@media screen and (min-width: 600px) {
#div1 {
font-size: 80px;
}
}
</style>
</head>
<body>
<div id="div1">Hello World</div>
<p>Resize the browser window to see the font size change at 600px.</p>
</body>
</html>
Медиазапросы для пользовательских предпочтений
Люди с чувствительностью к движению обычно предпочитают сайты с меньшим количеством анимации.
Запросил ли пользователь уменьшение движения, например меньше анимаций или переходов, можно проверить с помощью медиахарактеристики prefers-reduced-motion. Если эта настройка активна на его компьютере, эта характеристика позволяет отключить анимации и переходы.
Пример
Результат: полная HTML-страница
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reduced Motion Media Query</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.box {
width: 100px;
height: 100px;
background-color: coral;
position: relative;
animation: moveBox 3s infinite alternate;
}
@keyframes moveBox {
from { left: 0; }
to { left: 300px; }
}
@media (prefers-reduced-motion: reduce) {
* {
animation: none !important;
transition: none !important;
}
}
</style>
</head>
<body>
<h2>Prefers Reduced Motion</h2>
<p>If you have "reduce motion" enabled in your system settings, the box below will not animate.</p>
<div class="box"></div>
</body>
</html>