Responsive Design

С возвращением.
В предыдущем уроке ты изучил CSS Grid.
Rows.
Columns.
Cards, которые ведут себя как дисциплинированные маленькие коробки.
Очень хорошо.
Теперь нам нужно сделать так, чтобы эти layouts работали на разных screen sizes.
Потому что сайт, который красиво выглядит только на твоём laptop, ещё не готов.
Он просто уверен в себе в одной комнате.
Users могут открыть твой сайт на:
- phones;
- tablets;
- laptops;
- огромных monitors;
- маленьких старых screens;
- devices, которые выглядят так, будто кто-то приклеил browser к тостеру.
Responsive design помогает сайту адаптироваться.
Цель простая:
сделать page читаемой, удобной и приятной на каждом screen.
Без того, чтобы users должны были zoom-ить, scroll-ить sideways или сомневаться в твоих жизненных решениях.
Что Ты Изучишь
В этом уроке ты узнаешь:
- что означает responsive design;
- почему viewport meta tag важен;
- как использовать flexible widths;
- как делать images responsive;
- как использовать media queries;
- как применять mobile-first CSS;
- как менять layout на меньших screens;
- как адаптировать cards, text и navigation.
Что Такое Responsive Design?
Responsive design означает создание websites, которые адаптируются к разным screen sizes.
Desktop layout может иметь:
- wide sections;
- несколько columns;
- большой text;
- cards рядом друг с другом.
Mobile layout обычно требует:
- одну column;
- большие tap areas;
- readable text;
- меньше horizontal complexity;
- без sideways scrolling.
Responsive design — это не создание пяти разных сайтов.
Это создание одного flexible website.
Один website.
Много screens.
Меньше хаоса.
Больше достоинства.
Viewport Meta Tag
Responsive design начинается в HTML.
Внутри head должна быть эта строка:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Эта строка говорит browser:
Используй реальную ширину device и не делай вид, что phone — это маленький desktop.
Без этой строки mobile browsers могут странно масштабировать page.
Твой CSS может быть идеальным.
Но без viewport meta tag phone всё равно может вести себя так, будто нашёл твой layout в древней пещере.
Всегда добавляй его.
Создай Проект
Создай папку для этого урока:
mkdir css-lesson7
cd css-lesson7
touch index.html
touch style.css
Ты должен получить:
css-lesson7/
index.html
style.css
Открой папку в своём editor.
Мы построим маленькую responsive page с:
- header;
- navigation;
- hero section;
- cards;
- image;
- footer.
Потом сделаем так, чтобы она адаптировалась к smaller screens.
Без паники.
Только CSS.
Что иногда означает то же самое.
Но сегодня мы спокойны.
Напиши HTML
Открой index.html и добавь это:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Design</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="site-header">
<nav class="navbar">
<h1 class="logo">ResponsiveSite</h1>
<div class="nav-links">
<a href="#">Главная</a>
<a href="#">Курсы</a>
<a href="#">Проекты</a>
<a href="#">Контакт</a>
</div>
</nav>
<section class="hero">
<div class="hero-text">
<h2>Создавай Сайты для Каждого Экрана</h2>
<p>
Responsive design помогает layout адаптироваться к phones, tablets, laptops и большим monitors.
</p>
<a href="#" class="button">Начать Обучение</a>
</div>
<div class="hero-image">
<img src="https://via.placeholder.com/600x400" alt="Пример responsive design">
</div>
</section>
</header>
<main class="page">
<section class="intro">
<h2>Почему Responsive Design Важен</h2>
<p>
Люди заходят на websites с разных devices. Твой layout должен работать везде, а не только на твоём любимом screen.
</p>
</section>
<section class="cards">
<article class="card">
<h2>Flexible Layouts</h2>
<p>Используй flexible widths, Grid и Flexbox, чтобы создавать layouts, которые адаптируются.</p>
</article>
<article class="card">
<h2>Readable Text</h2>
<p>Text должен оставаться комфортным для чтения и на маленьких, и на больших screens.</p>
</article>
<article class="card">
<h2>Media Queries</h2>
<p>Используй media queries, чтобы менять styles на разных screen sizes.</p>
</article>
</section>
</main>
<footer class="site-footer">
<p>Создано во время изучения responsive design.</p>
</footer>
</body>
</html>
Этот HTML включает viewport meta tag.
Хорошо.
Твоя page уже лучше подготовлена для mobile screens, чем многие websites из 2009 года.
Маленькая победа.
Начни с Базового CSS
Открой style.css и добавь:
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: Arial, sans-serif;
background-color: #f3f4f6;
color: #111827;
}
a {
color: inherit;
text-decoration: none;
}
img {
max-width: 100%;
display: block;
}
Важная часть:
img {
max-width: 100%;
display: block;
}
Это делает images responsive.
Image не станет шире своего container.
Без этого большие images могут сломать layout.
Images — как очень энтузиастичные гости.
Хорошо, что они есть.
Но им нужны границы.
Стилизуй Header и Navbar
Добавь это:
.site-header {
background-color: #111827;
color: white;
}
.navbar {
max-width: 1100px;
margin: 0 auto;
padding: 24px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
}
.logo {
margin: 0;
font-size: 24px;
}
.nav-links {
display: flex;
gap: 20px;
font-weight: 700;
}
На desktop logo и links будут в одном row.
Это хорошо для wide screens.
Но на phones может не хватить места.
Мы исправим это позже через media query.
Пока что desktop layout.
Как построить стол перед тем, как решить, где будет сидеть кот.
Стилизуй Hero Section
Добавь:
.hero {
max-width: 1100px;
margin: 0 auto;
padding: 64px 24px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 40px;
align-items: center;
}
.hero-text h2 {
margin: 0 0 16px;
font-size: 48px;
line-height: 1.1;
}
.hero-text p {
color: #d1d5db;
font-size: 20px;
line-height: 1.7;
}
.button {
display: inline-block;
background-color: #2563eb;
color: white;
padding: 14px 20px;
border-radius: 999px;
font-weight: 700;
margin-top: 16px;
}
.hero-image img {
border-radius: 24px;
border: 2px solid #374151;
}
Hero использует Grid с двумя columns:
grid-template-columns: 1fr 1fr;
Это хорошо для desktop.
Text с одной стороны.
Image с другой.
Очень прилично.
Но на phone две columns могут стать слишком узкими.
Поэтому позже мы превратим их в одну column.
CSS должен учиться хорошим манерам.
Стилизуй Main Page
Добавь:
.page {
max-width: 1100px;
margin: 40px auto;
padding: 0 24px;
}
.intro {
background-color: white;
padding: 32px;
border-radius: 18px;
margin-bottom: 24px;
border-left: 6px solid #2563eb;
}
.intro h2 {
margin-top: 0;
font-size: 32px;
}
.intro p {
color: #4b5563;
font-size: 18px;
line-height: 1.7;
}
Это даёт content комфортную ширину.
max-width не позволяет page стать слишком широкой.
padding держит content подальше от краёв screen.
На phones side padding очень важен.
Text, который касается края screen, выглядит некомфортно.
Как стул с одной подозрительной ножкой.
Создай Responsive Cards
Добавь:
.cards {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 24px;
}
.card {
background-color: white;
padding: 28px;
border: 2px solid #e5e7eb;
border-radius: 18px;
}
.card h2 {
margin-top: 0;
font-size: 24px;
}
.card p {
color: #4b5563;
font-size: 18px;
line-height: 1.6;
}
На desktop мы показываем три cards в одном row.
Это хорошо.
Но на tablets и phones нужно меньше columns.
Вот тут входят media queries.
Media queries — это когда CSS говорит:
“При определённых условиях я буду вести себя иначе.”
Очень зрело.
Если бы все layouts были такими emotionally available.
Что Такое Media Query?
Media query позволяет применять CSS только тогда, когда определённые условия выполняются.
Пример:
@media (max-width: 800px) {
.cards {
grid-template-columns: 1fr;
}
}
Это означает:
Если screen имеет ширину 800px или меньше, сделай cards в одну column.
Media queries необходимы для responsive design.
Они позволяют layout адаптироваться.
Не паниковать.
Адаптироваться.
Большая разница.
Сделай Layout Responsive
Добавь это в конец CSS:
@media (max-width: 800px) {
.hero {
grid-template-columns: 1fr;
}
.cards {
grid-template-columns: repeat(2, 1fr);
}
.hero-text h2 {
font-size: 40px;
}
}
Теперь:
- hero становится одной column;
- cards становятся двумя columns;
- hero heading становится меньше.
Это лучше для tablets и smaller screens.
Ещё не идеально.
Но лучше.
Responsive design — это не один гигантский fix.
Это серия разумных решений.
Как жизнь.
Но с большим количеством semicolons.
Улучши Phone Layout
Добавь ещё одну media query:
@media (max-width: 560px) {
.navbar {
flex-direction: column;
align-items: flex-start;
}
.nav-links {
flex-direction: column;
gap: 12px;
}
.hero {
padding: 48px 20px;
}
.hero-text h2 {
font-size: 34px;
}
.hero-text p {
font-size: 18px;
}
.cards {
grid-template-columns: 1fr;
}
.intro,
.card {
padding: 24px;
}
}
Теперь на phones:
- navbar становится вертикальным;
- links становятся column;
- hero heading становится меньше;
- cards становятся одной column;
- spacing становится компактнее.
Это responsive design в действии.
Тот же HTML.
Другой layout в зависимости от screen.
Очень мощно.
Очень полезно.
Почти подозрительно цивилизованно.
Mobile-First CSS
Есть два распространённых подхода.
Desktop-first:
.cards {
grid-template-columns: repeat(3, 1fr);
}
@media (max-width: 560px) {
.cards {
grid-template-columns: 1fr;
}
}
Mobile-first:
.cards {
grid-template-columns: 1fr;
}
@media (min-width: 700px) {
.cards {
grid-template-columns: repeat(3, 1fr);
}
}
Mobile-first означает: сначала пишем mobile layout, а потом добавляем более широкие layouts для больших screens.
Это часто хороший подход.
Почему?
Потому что small screens имеют больше ограничений.
Если design работает на phone, расширить его для desktop обычно легче.
Как сначала собрать backpack, а потом переехать в house.
Не наоборот.
Flexible Widths
Избегай fixed widths, когда возможно.
Плохо:
.card {
width: 400px;
}
Это может сломаться на small screens.
Лучше:
.card {
width: 100%;
max-width: 400px;
}
Или позволь Grid контролировать width:
.cards {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
Fixed widths не всегда плохие.
Но их нужно использовать осторожно.
Fixed width на desktop может стать disaster на mobile.
CSS помнит всё.
А mobile показывает твои грехи.
Responsive Text
Большие desktop headings могут быть слишком большими на phones.
Desktop:
.hero-text h2 {
font-size: 48px;
}
Phone:
@media (max-width: 560px) {
.hero-text h2 {
font-size: 34px;
}
}
Это сохраняет text читаемым и не даёт ему захватить весь screen.
Большой text — это хорошо.
Text, который съедает весь phone screen — нет.
Это уже не heading.
Это hostage situation.
Полный CSS
Твой style.css должен выглядеть так:
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: Arial, sans-serif;
background-color: #f3f4f6;
color: #111827;
}
a {
color: inherit;
text-decoration: none;
}
img {
max-width: 100%;
display: block;
}
.site-header {
background-color: #111827;
color: white;
}
.navbar {
max-width: 1100px;
margin: 0 auto;
padding: 24px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
}
.logo {
margin: 0;
font-size: 24px;
}
.nav-links {
display: flex;
gap: 20px;
font-weight: 700;
}
.hero {
max-width: 1100px;
margin: 0 auto;
padding: 64px 24px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 40px;
align-items: center;
}
.hero-text h2 {
margin: 0 0 16px;
font-size: 48px;
line-height: 1.1;
}
.hero-text p {
color: #d1d5db;
font-size: 20px;
line-height: 1.7;
}
.button {
display: inline-block;
background-color: #2563eb;
color: white;
padding: 14px 20px;
border-radius: 999px;
font-weight: 700;
margin-top: 16px;
}
.hero-image img {
border-radius: 24px;
border: 2px solid #374151;
}
.page {
max-width: 1100px;
margin: 40px auto;
padding: 0 24px;
}
.intro {
background-color: white;
padding: 32px;
border-radius: 18px;
margin-bottom: 24px;
border-left: 6px solid #2563eb;
}
.intro h2 {
margin-top: 0;
font-size: 32px;
}
.intro p {
color: #4b5563;
font-size: 18px;
line-height: 1.7;
}
.cards {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 24px;
}
.card {
background-color: white;
padding: 28px;
border: 2px solid #e5e7eb;
border-radius: 18px;
}
.card h2 {
margin-top: 0;
font-size: 24px;
}
.card p {
color: #4b5563;
font-size: 18px;
line-height: 1.6;
}
.site-footer {
text-align: center;
padding: 32px 24px;
color: #6b7280;
}
@media (max-width: 800px) {
.hero {
grid-template-columns: 1fr;
}
.cards {
grid-template-columns: repeat(2, 1fr);
}
.hero-text h2 {
font-size: 40px;
}
}
@media (max-width: 560px) {
.navbar {
flex-direction: column;
align-items: flex-start;
}
.nav-links {
flex-direction: column;
gap: 12px;
}
.hero {
padding: 48px 20px;
}
.hero-text h2 {
font-size: 34px;
}
.hero-text p {
font-size: 18px;
}
.cards {
grid-template-columns: 1fr;
}
.intro,
.card {
padding: 24px;
}
}
Сохрани файл.
Обнови browser.
Измени размер window.
Layout должен меняться.
Desktop:
- navbar в одном row;
- hero в двух columns;
- cards в трёх columns.
Tablet:
- hero в одной column;
- cards в двух columns.
Phone:
- navbar stacked;
- cards в одной column;
- text меньше и легче для чтения.
Поздравляю.
Твой layout больше не боится phones.
Частые Ошибки
Забыть viewport meta tag
Без этого:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
mobile layout может вести себя плохо.
Всегда добавляй его.
Не торгуйся с этой строкой.
Она маленькая, но мощная.
Как крошечный CSS bodyguard.
Создать horizontal scrolling
Horizontal scrolling часто появляется, потому что что-то слишком широкое.
Распространённые причины:
- fixed width;
- большая image;
- длинный text без spaces;
- слишком много columns;
- отсутствует
max-width: 100%для images.
Если page scroll-ится sideways на mobile, расследуй.
Sideways scrolling — это обычно крик о помощи.
Слишком Маленький Text
Phone users не должны нуждаться в microscope.
Плохо:
p {
font-size: 12px;
}
Лучше:
p {
font-size: 16px;
line-height: 1.6;
}
Readable text важен.
Красивый layout с нечитаемым text — это просто decoration с trust issues.
Практика
Создай responsive page с:
- navbar;
- hero section;
- image;
- тремя cards;
- footer.
Сделай, чтобы она работала так:
- desktop: hero в двух columns, cards в трёх columns;
- tablet: hero в одной column, cards в двух columns;
- phone: navbar stacked, cards в одной column.
Используй:
max-width;grid-template-columns;media queries;max-width: 100%для images;- flexible spacing;
- меньшие headings на phones.
Тестируй, меняя размер browser.
Не доверяй только одному screen.
Один screen врёт.
Много screens говорят правду.
Мини-Задание
Возьми card grid из предыдущего урока.
Сделай его responsive:
- 3 columns на desktop;
- 2 columns ниже
800px; - 1 column ниже
560px.
Потом добавь responsive hero над ним.
Используй Grid для hero.
Используй Grid для cards.
Используй Flexbox для navbar.
Это реальный web layout pattern.
Ты не просто учишь theory.
Ты строишь structure, которую используют на real websites.
Layout взрослеет.
Постарайся не плакать.
Итог
Сегодня ты узнал, что:
- responsive design делает websites адаптивными к разным screens;
- viewport meta tag является essential;
- images обычно должны использовать
max-width: 100%; - fixed widths могут ломать mobile layouts;
- media queries применяют CSS только при определённых conditions;
- layouts часто требуют меньше columns на smaller screens;
- text sizes могут требовать изменений на phones;
- mobile-first CSS начинается с small screens и расширяется вверх;
- responsive design не является optional.
Website должен работать там, где users реально находятся.
А users везде.
Phones.
Tablets.
Laptops.
Странные devices.
Возможно, даже smart fridges.
Не строй только для своего screen.
Строй для real life.
Real life имеет много screen sizes и очень мало patience.
Следующий Урок
В следующем уроке мы изучим backgrounds, borders и shadows.
Мы сделаем sections, cards и buttons более polished.
Не overdecorated.
Polished.
Есть разница.
Очень важная разница.