← Back to course

Responsive Design

Responsive Design

З поверненням.

У попередньому уроці ти вивчив CSS Grid.

Rows.

Columns.

Cards, які поводяться як дисципліновані маленькі коробки.

Дуже добре.

Тепер нам треба зробити так, щоб ці layouts працювали на різних screen sizes.

Бо сайт, який виглядає красиво тільки на твоєму laptop, ще не готовий.

Він просто впевнений у собі в одній кімнаті.

Users можуть відкрити твій сайт на:

Responsive design допомагає сайту адаптуватися.

Ціль проста:

зробити page читабельною, зручною і приємною на кожному screen.

Без того, щоб users мусили zoom-ити, scroll-ити sideways або сумніватися в твоїх життєвих рішеннях.

Що Ти Вивчиш

У цьому уроці ти дізнаєшся:

Що Таке Responsive Design?

Responsive design означає створення websites, які адаптуються до різних screen sizes.

Desktop layout може мати:

Mobile layout зазвичай потребує:

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 з:

Потім зробимо так, щоб вона адаптувалася до smaller screens.

Без паніки.

Тільки CSS.

Що іноді означає те саме.

Але сьогодні ми спокійні.

Напиши HTML

Відкрий index.html і додай це:

<!DOCTYPE html>
<html lang="uk">
<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;
  }
}

Тепер:

Це краще для 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:

Це 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:

Tablet:

Phone:

Вітаю.

Твій layout більше не боїться phones.

Типові Помилки

Забути viewport meta tag

Без цього:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

mobile layout може поводитися погано.

Завжди додавай його.

Не торгуйся з цим рядком.

Він маленький, але потужний.

Як крихітний CSS bodyguard.

Створити horizontal scrolling

Horizontal scrolling часто з’являється, бо щось занадто широке.

Поширені причини:

Якщо 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 з:

Зроби, щоб вона працювала так:

Використай:

Тестуй, змінюючи розмір browser.

Не довіряй тільки одному screen.

Один screen бреше.

Багато screens кажуть правду.

Міні-Завдання

Візьми card grid з попереднього уроку.

Зроби його responsive:

Потім додай responsive hero над ним.

Використай Grid для hero.

Використай Grid для cards.

Використай Flexbox для navbar.

Це реальний web layout pattern.

Ти не просто вчиш theory.

Ти будуєш structure, яку використовують на real websites.

Layout дорослішає.

Постарайся не плакати.

Підсумок

Сьогодні ти дізнався, що:

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.

Є різниця.

Дуже важлива різниця.