Нажмите на код, чтобы скопировать его.
Flexbox и Grid - два основных способа верстки макетов в современном CSS. Оба мощные, но решают разные задачи.
| Критерий | Flexbox | Grid |
|---|---|---|
| Назначение | Одномерная компоновка (строка или столбец) | Двумерная компоновка (строки + столбцы) |
| Использование | Навигация, выравнивание элементов в ряд | Сетка страницы, карточки, формы, макеты |
| Направление | Главное направление: row или column |
Работает сразу по двум осям |
| Гибкость | Элементы растягиваются/сжимаются | Фиксированные или дробные единицы (fr) |
Идеален для:
<div class="flex-container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
.flex-container {
display: flex;
gap: 10px;
}
flex-direction: row; /* слева направо (по умолчанию) */
flex-direction: row-reverse; /* справа налево */
flex-direction: column; /* сверху вниз */
flex-direction: column-reverse; /* снизу вверх */
justify-content: flex-start; /* начало */
justify-content: center; /* по центру */
justify-content: flex-end; /* конец */
justify-content: space-between; /* равные отступы между */
justify-content: space-around; /* отступы вокруг */
justify-content: space-evenly; /* равные промежутки */
align-items: stretch; /* растянуть (по умолчанию) */
align-items: flex-start; /* в начало */
align-items: center; /* по центру */
align-items: flex-end; /* в конец */
align-items: baseline; /* по базовой линии текста */
.item {
flex: 1; /* занимает всё доступное пространство */
}
.item:nth-child(2) {
flex: 2; /* занимает вдвое больше */
}
flex-wrap: nowrap; /* не переносить (по умолчанию) */
flex-wrap: wrap; /* переносить на новую строку */
flex-wrap: wrap-reverse;
.center {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Идеален для:
<div class="grid-container">
<header>Шапка</header>
<aside>Меню</aside>
<main>Контент</main>
<footer>Подвал</footer>
</div>
.grid-container {
display: grid;
gap: 10px;
grid-template-columns: 200px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
height: 100vh;
}
/* Единицы измерения */
grid-template-columns: 100px 200px 1fr; /* фикс + дробный */
grid-template-columns: repeat(3, 1fr); /* 3 равные колонки */
grid-template-columns: 1fr 2fr; /* 1:2 */
grid-template-columns: minmax(100px, 1fr) 1fr; /* мин/макс */
/* Автоматическое создание колонок */
grid-auto-columns: 100px;
grid-auto-rows: 50px;
header { grid-area: header; }
aside { grid-area: sidebar; }
main { grid-area: main; }
footer { grid-area: footer; }
Или по линиям:
.item {
grid-column: 1 / 3; /* с 1 по 3 колонку */
grid-row: 2 / 4; /* со 2 по 4 строку */
}
justify-items: start | end | center | stretch; /* по горизонтали */
align-items: start | end | center | stretch; /* по вертикали */
justify-content: start | end | center | stretch | space-between | space-around;
align-content: ... /* когда строк больше, чем контента */
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}
Автоматически подстраивается под ширину экрана.
.modal-wrapper {
display: grid;
place-items: center;
position: fixed;
inset: 0;
background: rgba(0,0,0,0.5);
}
.modal {
background: white;
padding: 20px;
border-radius: 8px;
}
Да! Часто:
.page {
display: grid;
grid-template-columns: 250px 1fr;
grid-template-rows: 80px 1fr 60px;
height: 100vh;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 20px;
}
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 16px;
padding: 20px;
}
.card {
display: flex;
flex-direction: column;
gap: 8px;
padding: 16px;
border: 1px solid #ccc;
border-radius: 8px;
}
gap вместо margin - проще управлять отступами.place-items: center = justify-items + align-items.minmax() + auto-fit = идеальная адаптивная сетка.flex: 1 растягивает элемент на всё свободное место.