From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../basic_concepts_of_grid_layout/index.html | 699 +++++++++++++++++++++ files/uk/web/css/css_grid_layout/index.html | 245 ++++++++ .../relationship_of_grid_layout/index.html | 628 ++++++++++++++++++ 3 files changed, 1572 insertions(+) create mode 100644 files/uk/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html create mode 100644 files/uk/web/css/css_grid_layout/index.html create mode 100644 files/uk/web/css/css_grid_layout/relationship_of_grid_layout/index.html (limited to 'files/uk/web/css/css_grid_layout') diff --git a/files/uk/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html b/files/uk/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html new file mode 100644 index 0000000000..84c95201bb --- /dev/null +++ b/files/uk/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html @@ -0,0 +1,699 @@ +--- +title: Основна концепція макета grid +slug: Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout +tags: + - CSS Grid + - Посібник +translation_of: Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout +--- +

CSS Grid Layout вводить двовимірну сітку до CSS. Сітки можуть бути використані для виділення основних областей сторінки або невеликих елементів інтерфейсу користувача. У цій статті надана схема CSS Grid Layout та нова термінологія, що є частиною специфікації CSS Grid Layout Level 1. Функції, наведені в цьому огляді, будуть більш детально пояснені далі в цьому посібнику.

+ +

Що таке grid?

+ +

Grid є перехресним набором  горизонтальних і вертикальних ліній, що перетинаються - один набір визначає стовпці,  інший рядки. Елементи можуть бути розміщені на сітці, дотримуючись цих стовпців та рядків. Макет сітки CSS має такі особливості:

+ +

Фіксовані та гнучкі розміри смуг

+ +

Ви можете створити сітку з фіксованими розмірами смуг – наприклад, використовуючи пікселі. Це встановлює сітку на певні пікселі, що відповідають бажаному макету. Ви також можете створити сітку з використанням гнучких розмірів у відсотках або з новою одиницею fr, яку розроблену саме для цієї мети.

+ +

Розміщення елементів

+ +

Ви можете розміщувати елементи у точному місці сітки, використовуючи номери рядків, імена або орієнтуючись на область сітки. Сітка також містить алгоритм для контролю розміщення елементів, які не мають явного положення на сітці.

+ +

Створення додаткових смуг для вмісту

+ +

Ви можете визначати сітку явно в макеті сітки, але специфікація також стосується вмісту, доданого за межами оголошеної сітки, додаючи додаткові рядки та стовпчики за потребою. Спрацьовує принцип додавання " стільки стовпчиків, скільки вміститься в контейнер".

+ +

Управління вирівнюванням

+ +

Сітка містить функції вирівнювання для того, щоб ми могли контролювати, як вирівнюються розміщені в області сітки елементи  та як вирівнюється вся Grid-сітка.

+ +

Управління вмістом, що перекривається

+ +

У секцію сітки можна додати більш ніж один елемент. Також області можуть частково перекривати одна одну. Цим накладенням можна керувати за допомогою {{cssxref("z-index")}} властивості.

+ +

Grid - це потужна специфікація, яка у поєднанні з іншими можливостями CSS такими, як flexbox, дозволяє вам створювати макети, які раніше неможливо було створити за допомогою CSS. Все починається шляхом створення сітки у grid-контейнері.

+ +

Grid-контейнер

+ +

Ми створюємо grid-контейнер оголошуючи display: grid або display: inline-grid на елементі. Як тільки ми це зробимо, всі прямі діти елементу стають grid-елементами.

+ +

У цьому прикладі, у мене div-елемент з класом wrapper, що містить в собі п'ять дочірніх елементів.

+ +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +

Я роблю з класу .wrapper grid-контейнер.

+ +
.wrapper {
+  display: grid;
+}
+
+ + + +

{{ EmbedLiveSample('The_Grid_container', '200', '330') }}

+ +

Всі прямі нащадки тепер є grid-елементами. В браузері ви не помітите ніякої різниці між виглядом елементів до і після створення grid-контейнеру. З цієї точки зору вам буде корисно працювати в редакторі Firefox Developer Edition, який має Grid Inspector, доступний як частина інструментів розробника. Якщо ви розглянете цей приклад в  Firefox і перевірите grid, ви побачите маленький значок біля значення grid. Клікніть його і сітка накладеться на цей елемент у вікні браузера.

+ +

Using the Grid Highlighter in DevTools to view a grid

+ +

Як вийде - працюйте з  CSS Grid Layout, це інструмент надасть вам краще розуміння того що відбувається з вашою grid-сіткою візуально. 

+ +

Якщо ми хочемо щоб це було більше grid-орієнтовано, треба додавати більше смуг-стовбців.

+ +

Grid Смуги

+ +

Ми визначаємо рядки і стовпчики на нашій grid-сітці  властивостями {{cssxref("grid-template-columns")}} та {{cssxref("grid-template-rows")}}. Вони визначають grid смуги. Grid-смуга – це простір будь якими двома лініями на grid-сітці. На зображенні нижче кольорова смуга – перша смуга-рядок на нашій grid-сітці.

+ +

+ +

До попереднього прикладу можна додати властивість  grid-template-columns, визначаючи розмір смуг-стовпчиків.

+ +

Таким чином створено grid-сітку з трьома смугами-стовпчиками шириною по 200 рх. Дочірні елементи вкладатимуться в цю grid-сітку в кожну клітинку. 

+ +
+
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 200px 200px 200px;
+}
+
+ + + +

{{ EmbedLiveSample('grid_first', '610', '140') }}

+
+ +

Одиниця fr 

+ +

Смуги визначаються одиницями довжини. Grid-сітка має додаткову одиницю довжини яка допомагає створювати гнучкі grid-смуги. Одиниця fr  являє собою частку вільного простору в  grid-контейнері. Наступна сітка створює три рівних по ширині смуги які  стають більше і менше відповідно наявному простору. 

+ +
+
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 1fr 1fr 1fr;
+}
+
+ + + +

{{ EmbedLiveSample('fr_unit_ls', '220', '140') }}

+
+ +

В наступному прикладі ми створюємо визначення з 2fr смугою і дві 1fr смуги. Доступний простір розділений на чотири частини, дві з яких надаються першій смузі і по одній частині кожній з наступних двох.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 2fr 1fr 1fr;
+}
+
+ +

В останньому прикладі ми комбінуємо абсолютні одиниці ширини смуг з фракційними. Перша смуга  500 px, фіксована ширина відбирається з доступного простору. Решта простору ділиться на три і призначається двом гнучким смугам пропорційно. 

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 500px 1fr 2fr;
+}
+
+ +

Визначення смуг зі значенням repeat()

+ +

Великі grid-сітки з багатьма стугами можуть використовувати значення repeat() для скорочення при визначенні стовпчиків: 

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 1fr 1fr 1fr;
+}
+
+ +

Також може бути записано як:

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+}
+
+ +

Значення repeat може використовуватись лише для частини стовпчиків. В наступному прикладі ініційовано смугу 20 рх, секцію з 6 смуг шириною 1fr, і смугу 20 рх. 

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 20px repeat(6, 1fr) 20px;
+}
+
+ +

Значення repeat визначає смуги, тобто його можливо використовувати для створення цілих шаблонів стовпчиків. В наступному прикладі grid-сітка складається з 10 смуг. Смуга 1fr , смуга 2fr і так п'ять разів.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(5, 1fr 2fr);
+}
+
+ +

Неявна і явна Grid-сітка

+ +

Cтворюючи Grid-сітку нашого прикладу, ми визначили стовпчики-смуги властивістю {{cssxref("grid-template-columns")}}, але дозволимо grid-сітці створювати рядки так, як краще для контенту. Такі рядки створюються в неявній grid-сітці. Явна grid-сітка складається з рядків і стовпчиків, які визначаються властивостями  {{cssxref("grid-template-columns")}} та {{cssxref("grid-template-rows")}}.

+ +

Якщо ми розташовуємо щось поза цією grid-сіткою, або кількість вмісту потребує більше grid смуг, тоді  grid-сітка створює рядки і стовпчики в неявній  grid-сітці. Такі смуги матимуть авторозмір за замовчуванням якраз щоб вмістити свій контент.

+ +

Ви також можете визначити встановлений розмір для смуг, створених в неявній grid-сітці властивостями {{cssxref("grid-auto-rows")}} та {{cssxref("grid-auto-columns")}}.

+ +

В прикладі нижче ми використовуємо grid-auto-rows  щоб забезпечити неявне створення смуги висотою 200 рх.

+ +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: 200px;
+}
+
+ + + +

{{ EmbedLiveSample('The_implicit_and_explicit_grid', '230', '420') }}

+ +

Розміри смуги і minmax()

+ +

Встановлюючи явну grid-сітку або визначаючи розміри для автоматично створених рядків або стовпчиків може виникнути необхідність надання смугам мінімального розміру. Але треба переконатись що розширюючись, вони відповідатимуть будь якому доданому контенту. Наприклад ми хочемо щоб рядки ніколи не були менше 100 рх, але якщо контент розширюється до 300 рх, ми б хотіли щоб рядок розширився до такої висоти. 

+ +

Grid для таких випадків має функцію {{cssxref("minmax", "minmax()")}}. В наступному прикладі я використовую minmax()в значенні {{cssxref("grid-auto-rows")}}. Це означає, що автоматично створені рядки матимуть мінімальну висоту 100 рх, а максимальну auto. Використання auto означає, що розмір буде підлаштовуватись під розмір контенту таким чином, щоб вмістити найвищий елемент в цьому рядку.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: minmax(100px, auto);
+}
+
+ + + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two
+    <p>I have some more content in.</p>
+    <p>This makes me taller than 100 pixels.</p>
+  </div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+ +

{{ EmbedLiveSample('Track_sizing_and_minmax()', '240', '470') }}

+ +

Grid Лінії

+ +

Варто зауважити що коли ми визначаємо Grid, ми визначаємо grid-смуги (але не grid-лінії). В такому випадку Grid дає нам нумеровані лінії для позиціонування елементів. В прикладі нижче Grid має 3 стовпчика, 2 рядки і 4 вертикальних лінії.

+ +

Diagram showing numbered grid lines.

+ +

Лінії пронумеровано згідно способу нумерації документа: зліва направо і зверху вниз (якщо на мові що викоричтовується пишуть справа наліво, то і нумерація ліній справа наліво). Лінії також можуть бути поіменовані.

+ +

Позиціонування елементів по лініях

+ +

Наступний приклад демонструє просте позиціонування елементів по лініях. При розміщенні елементів ми надаємо перевагу більше лініям ніж смугам.

+ +

В наступному прикладі ми розміщуємо перші два елементи на Grid-cітці, яка складається з трьох смуг-стовпчиків, застосовуючи властивості {{cssxref("grid-column-start")}}, {{cssxref("grid-column-end")}}, {{cssxref("grid-row-start")}} та {{cssxref("grid-row-end")}}.  Рухаючись зліва направо, перший елемент починається з вертикальної лініі 1 і простягається до вертикальної лініі 4, що праворуч нашої Grid-сітки. Він починається на горизонтальній лінії 1 і закінчується на горизонтальній лінії 3, тобто займає два рядка смуг.

+ +

Другий елемент починається з вертикальної лініі 1, і простягається на одну смугу. Це за замовчуванням, тому можна не вказувати кінцеву лінію. Також по рядках він простягається з горизонтальній лінії 3 до горизонтальній лінії 5. Інші елементи розміщуються в порожніх просторах на Grid-сітці.

+ +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three</div>
+  <div class="box4">Four</div>
+  <div class="box5">Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: 100px;
+}
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+}
+.box2 {
+  grid-column-start: 1;
+  grid-row-start: 3;
+  grid-row-end: 5;
+}
+
+ + + +

{{ EmbedLiveSample('Positioning_items_against_lines', '230', '420') }}

+ +

Не забуваймо, що можна використовувати Grid Inspector в Firefox Developer Tools щоб побачити як елементи позиціонуються на лініях Grid-сітки.

+ +

Grid-клітини

+ +

Grid-клітина – найменша одиниця Grid-сітки, по аналогії з чарунком таблиці. Як ми бачили в попередніх прикладах, якщо Grid-сітка визначена як батьківська, дочірні елементи лежатимуть по одному в кожній її клітині. На зображенні кольором позначено першу клітину Grid-сітки.

+ +

The first cell of the grid highlighted

+ +

Grid-ділянки

+ +

Елементи можуть розташовуватись на одній або декількох клітинках як в рядок так і в стовпчик, і це створює Grid-ділянки. Grid-ділянки завжди прямокутні, неможлива, наприклад, L-подібна Grid-ділянка. На зображенні Grid-ділянка займає два рядки і два стовпчики.

+ +

A grid area

+ +

Розриви

+ +

Розриви між Grid-клітинами створюються властивістями {{cssxref("grid-column-gap")}} та {{cssxref("grid-row-gap")}}, або скорочено {{cssxref("grid-gap")}}. В наступному прикладі створюється проміжок у 10рх між стовпчиками та проміжок 1em між рядками. 

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  column-gap: 10px;
+  row-gap: 1em;
+}
+ +
+

Примітка: Коли гріди тільки почали використовуватись браузерами {{cssxref("column-gap")}}, {{cssxref("row-gap")}} та {{cssxref("gap")}} мали префікси grid- як от {{cssxref("grid-column-gap")}}, {{cssxref("grid-row-gap")}} та {{cssxref("grid-gap")}} відповідно.

+ +

Браузери наразі оновлюються, щоб видалити цей префікс, проте попередньо встановлені версії також будуть підтримуватися як псевдоніми, що робить їх безпечними для використання. В даний час деякі веб-переглядачі не підтримують безпрефіксний варіант, тому в прикладах цього посібника використовуюється версія з grid- префіксом.

+
+ +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+ + + +

{{ EmbedLiveSample('Gutters') }}

+ +

Будь-який простір, відведений на розриви, буде враховуватись до відведення простору для гнучких fr довжин смуг. Розриви використовуваються в розмітці, як звичайні grid-смуги, за виключенням того, що ви не зможете в них нічого помістити. З точки зору лінійного позиціонування розрив діє як товста лінія.

+ +

Вкладені Grid-сітки

+ +

Grid-елементи можуть ставати Grid-контейнерами. В попередньому прикладі ми створили Grid-сітку з трьох стовпчиків з двома позиціонованими елементами.  Перший з них має піделементи. Оскільки ці елементи не є прямими нащадками, вони не беруть участі в  Grid-розкладці і відображаються в нормальному потоці. 

+ +
+
<div class="wrapper">
+  <div class="box box1">
+    <div class="nested">a</div>
+    <div class="nested">b</div>
+    <div class="nested">c</div>
+  </div>
+  <div class="box box2">Two</div>
+  <div class="box box3">Three</div>
+  <div class="box box4">Four</div>
+  <div class="box box5">Five</div>
+</div>
+
+ +

Nested grid in flow

+ +

Якщо застосувати display: grid до box1, то ця Grid-смуга також стане Grid-сіткою. А елементи, що в ній містяться, надалі розташовуватимуться на цій новій Grid-сітці.

+ +
.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+}
+ + +
+ +

{{ EmbedLiveSample('nesting', '600', '340') }}

+ +

В цьому випадку, дочірня сітка немає відношення до батьківської. Як ви можете бачити на прикладі, вона не наслідує батьківськи {{cssxref("grid-gap")}}, а також лінії дочірньої сітки не вирівнюються по лініях батьківської сітки.

+ +

Під-сітка

+ +

У робочій чорнетці специфікації Grid Level 2 є функція під назвою subgrid, яка має дозволити нам створювати вкладені сітки, які б використовували визначення смуги батьківської сітки.

+ +
+

Примітка: під-сітки ще не реалізовані в жодному браузері, і їхня специфікація ще може змінюватися.

+
+ +

У поточній специфікації ми відредагуємо вищезгаданий приклад вкладеної Grid-сітки, змінивши визначення смуги з grid-template-columns: repeat(3, 1fr) , на grid-template-columns: subgrid. Вкладена сітка надалі використовуватиме батьківські Grid-смуги до елементів макета.

+ +
.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  display: grid;
+  grid-template-columns: subgrid;
+}
+ +

Нашарування елементів за допомогою z-index

+ +

Grid-елементи можуть займати одну і ту ж саму клітину. Якщо повернутись до нашого прикладу з елементами, що розташовані за номером рядка, ми можемо змінити його так, щоб два елементи перекривали один одного.

+ +
+
<div class="wrapper">
+  <div class="box box1">One</div>
+  <div class="box box2">Two</div>
+  <div class="box box3">Three</div>
+  <div class="box box4">Four</div>
+  <div class="box box5">Five</div>
+</div>
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: 100px;
+}
+
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+}
+
+.box2 {
+  grid-column-start: 1;
+  grid-row-start: 2;
+  grid-row-end: 4;
+}
+ + +
+ +

{{ EmbedLiveSample('l_ex', '230', '420') }}

+ +

Елемент box2 тепер перекриває box1, він відображається зверху, тому що пізніше трапляеться в коді документу.

+ +

Керування послідовністю

+ +

Ми можемо контролювати порядок, в якому елементи накладаються один на одного, використовуючи властивість z-index. Якщо надати box2 нижчий z-index, ніж в box1, то він і буде показаний нижче у стеці.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: 100px;
+}
+
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  z-index: 2;
+}
+
+.box2 {
+  grid-column-start: 1;
+  grid-row-start: 2;
+  grid-row-end: 4;
+  z-index: 1;
+}
+
+ + + +

{{ EmbedLiveSample('Controlling_the_order', '230', '420') }}

+ +

Наступні кроки

+ +

У цій статті ми швидко переглянули специфікацію Grid Layout. Пограйте з прикладами коду, а потім переходьте до наступної частини цього посібника, де ми насправді почнемо заглиблюватись в деталі CSS Grid Layout.

+ + diff --git a/files/uk/web/css/css_grid_layout/index.html b/files/uk/web/css/css_grid_layout/index.html new file mode 100644 index 0000000000..e403f8364f --- /dev/null +++ b/files/uk/web/css/css_grid_layout/index.html @@ -0,0 +1,245 @@ +--- +title: CSS Grid Layout +slug: Web/CSS/CSS_Grid_Layout +tags: + - CSS + - Grid Layout + - Grids + - Layout + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/CSS/CSS_Grid_Layout +--- +

CSS Grid layout відзначається тим, що розділяє сторінку на ділянки чи задає співвідношення між елементами, побудованими з HTML примітивів, з точки зору розміру, положення та слоїв.

+ +

Подібно до таблиць, CSS Grid дозволяє автору вирівнювати елементи у стовпчиках та рядках. Однак, CSS Grid, в порівнянні з таблицями, надає більше можливостей і полегшує створення макетів. Наприклад, дочірні елементи Grid-контейнера можуть перекривати один одного і нашаровуватись, подібно до позиційованих CSS елементів.

+ +

Базовий приклад

+ +

У наведеному нижче прикладі показана сітка з трьома стовпчиками, в якій нові рядки мають мінімальну висоту 100 пікселів, а максимальна висота вираховується автоматично. Елементи розміщені в сітці використовуючи лінійне розташування .

+ +
+ + +

HTML

+ +
<div class="wrapper">
+  <div class="one">One</div>
+  <div class="two">Two</div>
+  <div class="three">Three</div>
+  <div class="four">Four</div>
+  <div class="five">Five</div>
+  <div class="six">Six</div>
+</div>
+ +

CSS

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-gap: 10px;
+  grid-auto-rows: minmax(100px, auto);
+}
+.one {
+  grid-column: 1 / 3;
+  grid-row: 1;
+}
+.two {
+  grid-column: 2 / 4;
+  grid-row: 1 / 3;
+}
+.three {
+  grid-column: 1;
+  grid-row: 2 / 5;
+}
+.four {
+  grid-column: 3;
+  grid-row: 3;
+}
+.five {
+  grid-column: 2;
+  grid-row: 4;
+}
+.six {
+  grid-column: 3;
+  grid-row: 4;
+}
+
+ +

{{ EmbedLiveSample('example', '500', '440') }}

+
+ +

Посилання

+ +

CSS властивості

+ +
+ +
+ +

CSS функції

+ +
+ +
+ +

Глосарій

+ +
+ +
+ +

Посібники

+ +
+ +
+ +

Зовнішні ресурси

+ + + +

Специфікації

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Grid') }}{{ Spec2('CSS3 Grid') }}Initial definition.
+ + diff --git a/files/uk/web/css/css_grid_layout/relationship_of_grid_layout/index.html b/files/uk/web/css/css_grid_layout/relationship_of_grid_layout/index.html new file mode 100644 index 0000000000..7f715c0986 --- /dev/null +++ b/files/uk/web/css/css_grid_layout/relationship_of_grid_layout/index.html @@ -0,0 +1,628 @@ +--- +title: Relationship of grid layout to other layout methods +slug: Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout +translation_of: Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout +--- +

CSS Grid Layout has been designed to work alongside other parts of CSS, as part of a complete system for doing the layout. In this guide, I will explain how a grid fits together with other techniques you may already be using.

+ +

Grid and flexbox

+ +

The basic difference between CSS Grid Layout and CSS Flexbox Layout is that flexbox was designed for layout in one dimension - either a row or a column. Grid was designed for two-dimensional layout - rows, and columns at the same time. The two specifications share some common features, however, and if you have already learned how to use flexbox, the similarities should help you get to grips with Grid.

+ +

Одновимірні макети проти двовимірних

+ +

A simple example can demonstrate the difference between one- and two-dimensional layouts.

+ +

In this first example, I am using flexbox to lay out a set of boxes. I have five child items in my container, and I have given the flex properties values so that they can grow and shrink from a flex-basis of 200 pixels.

+ +

I have also set the {{cssxref("flex-wrap")}} property to wrap, so that if the space in the container becomes too narrow to maintain the flex basis, items will wrap onto a new row.

+ +
+ + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: flex;
+  flex-wrap: wrap;
+}
+.wrapper > div {
+  flex: 1 1 200px;
+}
+
+
+ +

{{ EmbedLiveSample('onedtwod', '500', '230') }}

+ +

In the image, you can see that two items have wrapped onto a new line. These items are sharing the available space and not lining up underneath the items above. This is because when you wrap flex items, each new row (or column when working by column) becomes a new flex container. Space distribution happens across the row.

+ +

A common question then is how to make those items line up. This is where you want a two-dimensional layout method: You want to control the alignment by row and column, and this is where grid comes in.

+ +

The same layout with CSS grids

+ +

In this next example, I create the same layout using Grid. This time we have three 1fr column tracks. We do not need to set anything on the items themselves; they will lay themselves out one into each cell of the created grid. As you can see they stay in a strict grid, lining up in rows and columns. With five items, we get a gap on the end of row two.

+ +
+ + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+}
+
+ +

{{ EmbedLiveSample('Two_Dimensional_With_Grid', '300', '170') }}

+
+ +

A simple question to ask yourself when deciding between grid or flexbox is:

+ + + +

Content out or layout in?

+ +

In addition to the one-dimensional versus two-dimensional distinction, there is another way to decide if you should use flexbox or grid for a layout. Flexbox works from the content out. An ideal use case for flexbox is when you have a set of items and want to space them out evenly in a container. You let the size of the content decide how much individual space each item takes up. If the items wrap onto a new line, they will work out their spacing based on their size and the available space on that line.

+ +

Grid works from the layout in. When you use CSS Grid Layout you create a layout and then you place items into it, or you allow the auto-placement rules to place the items into the grid cells according to that strict grid. It is possible to create tracks that respond to the size of the content, however, they will also change the entire track.

+ +

If you are using flexbox and find yourself disabling some of the flexibility, you probably need to use CSS Grid Layout. An example would be if you are setting a percentage width on a flex item to make it line up with other items in a row above. In that case, a grid is likely to be a better choice.

+ +

Box alignment

+ +

The feature of flexbox that was most exciting to many of us was that it gave us proper alignment control for the first time. It made it easy to center a box on the page. Flex items can stretch to the height of the flex container, meaning that equal height columns were possible. These were things we have wanted to do for a very long time, and have come up with all kinds of hacks to at least create the visual effect of.

+ +

The alignment properties from the flexbox specification have been added to a new specification called Box Alignment Level 3. This means that they can be used in other specifications, including Grid Layout. In the future, they may well apply to other layout methods as well.

+ +

In a later guide in this series, I’ll be taking a proper look at Box Alignment and how it works in Grid Layout. For now, here is a comparison between simple examples of flexbox and grid.

+ +

In the first example, which uses flexbox, I have a container with three items inside. The wrapper {{cssxref("min-height")}} is set, so it defines the height of the flex container. I have set {{cssxref("align-items")}} on the flex container to flex-end so the items will line up at the end of the flex container. I have also set the {{cssxref("align-self")}} property on box1 so it will override the default and stretch to the height of the container and on box2 so it aligns to the start of the flex container.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three</div>
+</div>
+
+ +
.wrapper {
+  display: flex;
+  align-items: flex-end;
+  min-height: 200px;
+}
+.box1 {
+  align-self: stretch;
+}
+.box2 {
+  align-self: flex-start;
+}
+
+ +

{{ EmbedLiveSample('Box_alignment', '300', '230') }}

+ +

Alignment in CSS Grids

+ +

This second example uses a grid to create the same layout. This time we are using the box alignment properties as they apply to a grid layout. So we align to start and end rather than flex-start and flex-end. In the case of a grid layout, we are aligning the items inside their grid area. In this case that is a single grid cell, but it could be an area made up of several grid cells.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3,1fr);
+  align-items: end;
+  grid-auto-rows: 200px;
+}
+.box1 {
+  align-self: stretch;
+}
+.box2 {
+  align-self: start;
+}
+
+ +

{{ EmbedLiveSample('Alignment_in_CSS_Grids', '200', '310') }}

+ +

The fr unit and flex-basis

+ +

We have already seen how the fr unit works to assign a proportion of available space in the grid container to our grid tracks. The fr unit, when combined with the {{cssxref("minmax", "minmax()")}} function can give us very similar behavior to the flex properties in flexbox while still enabling the creation of a layout in two dimensions.

+ +

If we look back at the example where I demonstrated the difference between one and two-dimensional layouts, you can see there is a difference between the way of the two layouts work responsively. With the flex layout, if we drag our window wider and smaller, the flexbox does a nice job of adjusting the number of items in each row according to the available space. If we have a lot of space all five items can fit on one row. If we have a very narrow container we may only have space for one.

+ +

In comparison, the grid version always has three column tracks. The tracks themselves will grow and shrink, but there are always three since we asked for three when defining our grid.

+ +

Auto-filling grid tracks

+ +

We can create a similar effect to flexbox, while still keeping the content arranged in strict rows and columns, by creating our track listing using repeat notation and the auto-fill and auto-fit properties.

+ +

In this next example, I have used the auto-fill keyword in place of an integer in the repeat notation and set the track listing to 200 pixels. This means that grid will create as many 200 pixels column tracks as will fit in the container.

+ + + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, 200px);
+}
+
+ +

{{ EmbedLiveSample('Auto-filling_grid_tracks', '500', '170') }}

+ +

A flexible number of tracks

+ +

This isn’t quite the same as flexbox. In the flexbox example, the items are larger than the 200 pixel basis before wrapping. We can achieve the same in grid by combining auto-fill and the {{cssxref("minmax", "minmax()")}} function. In this next example, I create auto filled tracks with minmax. I want my tracks to be a minimum of 200 pixels, so I set the maximum to be 1fr. Once the browser has worked out how many times 200 pixels will fit into the container–also taking account of grid gaps–it will treat the 1fr maximum as an instruction to share out the remaining space between the items.

+ + + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+}
+
+ +

{{ EmbedLiveSample('A_flexible_number_of_tracks', '500', '170') }}

+ +

We now have the ability to create a grid with a flexible number of flexible tracks, but see items laid out on the grid aligned by rows and columns at the same time.

+ +

Grid and absolutely positioned elements

+ +

Grid interacts with absolutely positioned elements, which can be useful if you want to position an item inside a grid or grid area. The specification defines the behavior when a grid container is a containing block and a parent of the absolutely positioned item.

+ +

A grid container as containing block

+ +

To make the grid container a containing block you need to add the position property to the container with a value of relative, just as you would make a containing block for any other absolutely positioned items. Once you have done this, if you give a grid item position: absolute it will take as its containing block the grid container or, if the item also has a grid position, the area of the grid it is placed into.

+ +

In the below example I have a wrapper containing four child items. Item three is absolutely positioned and also placed on the grid using line-based placement. The grid container has position: relative and so becomes the positioning context of this item.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">
+   This block is absolutely positioned. In this example the grid container is the containing block and so the absolute positioning offset values are calculated in from the outer edges of the area it has been placed into.
+  </div>
+  <div class="box4">Four</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(4,1fr);
+  grid-auto-rows: 200px;
+  grid-gap: 20px;
+  position: relative;
+}
+.box3 {
+  grid-column-start: 2;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  position: absolute;
+  top: 40px;
+  left: 40px;
+}
+
+ +

{{ EmbedLiveSample('A_grid_container_as_containing_block', '500', '330') }}

+ +

You can see that the item is taking the area from grid row line 2 to 4, and starting after line 1. Then it is offset in that area using the top and left properties. However, it has been taken out of flow as is usually for absolutely positioned items and so the auto-placement rules now place items into the same space. The item also doesn’t cause the additional row to be created to span to row line 3.

+ +

If we remove position: absolute from the rules for .box3 you can see how it would display without the positioning.

+ +

A grid container as parent

+ +

If the absolutely positioned child has a grid container as a parent but that container does not create a new positioning context, then it is taken out of flow as in the previous example. The positioning context will be whatever element creates a positioning context as is common to other layout methods. In our case, if we remove position: relative from the wrapper above, positioning context is from the viewport, as shown in this image.

+ +

Image of grid container as parent

+ +

Once again the item no longer participates in the grid layout in terms of sizing or when other items are auto-placed.

+ +

With a grid area as the parent

+ +

If the absolutely positioned item is nested inside a grid area then you can create a positioning context on that area. In the below example we have our grid as before but this time I have nested an item inside .box3 of the grid.

+ +

I have given .box3 position relative and then positioned the sub-item with the offset properties. In this case, the positioning context is the grid area.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three
+    <div class="abspos">
+     This block is absolutely positioned. In this example the grid area is the containing block and so the absolute positioning offset values are calculated in from the outer edges of the grid area.
+    </div>
+  </div>
+  <div class="box4">Four</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(4,1fr);
+  grid-auto-rows: 200px;
+  grid-gap: 20px;
+}
+.box3 {
+  grid-column-start: 2;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  position: relative;
+}
+.abspos {
+  position: absolute;
+  top: 40px;
+  left: 40px;
+  background-color: rgba(255,255,255,.5);
+  border: 1px solid rgba(0,0,0,0.5);
+  color: #000;
+  padding: 10px;
+}
+
+ +

{{ EmbedLiveSample('With_a_grid_area_as_the_parent', '500', '420') }}

+ +

Grid and display: contents

+ +

A final interaction with another layout specification that is worth noting is the interaction between CSS Grid Layout and display: contents. The contents value of the display property is a new value that is described in the Display specification as follows:

+ +
+

“The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal. For the purposes of box generation and layout, the element must be treated as if it had been replaced with its children and pseudo-elements in the document tree.”

+
+ +

If you set an item to display: contents the box it would normally create disappears, and the boxes of the child elements appear as if they have risen up a level. This means that children of a grid item can become grid items. Sound odd? Here is a simple example. In the following markup, I have a grid and the first item on the grid is set to span all three column tracks. It contains three nested items. As these items are not direct children, they don’t become part of the grid layout and so display using regular block layout.

+ +
+ + +
<div class="wrapper">
+  <div class="box box1">
+    <div class="nested">a</div>
+    <div class="nested">b</div>
+    <div class="nested">c</div>
+  </div>
+  <div class="box box2">Two</div>
+  <div class="box box3">Three</div>
+  <div class="box box4">Four</div>
+  <div class="box box5">Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: minmax(100px, auto);
+}
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+}
+
+
+ +

{{ EmbedLiveSample('Display_Contents_Before', '400', '420') }}

+
+ +

If I now add display: contents to the rules for box1, the box for that item vanishes and the sub-items now become grid items and lay themselves out using the auto-placement rules.

+ +
+ + +
<div class="wrapper">
+  <div class="box box1">
+    <div class="nested">a</div>
+    <div class="nested">b</div>
+    <div class="nested">c</div>
+  </div>
+  <div class="box box2">Two</div>
+  <div class="box box3">Three</div>
+  <div class="box box4">Four</div>
+  <div class="box box5">Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: minmax(100px, auto);
+}
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  display: contents;
+}
+
+ +

{{ EmbedLiveSample('Display_Contents_After', '400', '330') }}

+
+ +

This can be a way to get items nested into the grid to act as if they are part of the grid, and is a way around some of the issues that would be solved by subgrids once they are implemented. You can also use display: contents in a similar way with flexbox to enable nested items to become flex items.

+ +

As you can see from this guide, CSS Grid Layout is just one part of your toolkit. Don’t be afraid to mix it with other methods of doing layout to get the different effects you need.

+ +

See Also

+ + + + -- cgit v1.2.3-54-g00ecf