CSS flex-direction — напрямок осі флекс-контейнера
CSS властивість flex-direction встановлює напрямок головної осі батьківського контейнера. На напрямок також впливає значення атрибута dir у контейнера.
Зверніть увагу, що кінцеве значення властивості залежить від початкового напрямку осі контейнеру. Якщо атрибут dir дорівнює ltr, flex-direction зі значенням row розміщує елементи в порядку з ліва на право і row-reverse з права на ліво; якщо атрибут dir дорівнює rtl, flex-direction зі значенням row розміщує елементи в порядку з права на ліво і row-reverse з ліва на право.
Загальний опис
автор: NagarD
- Нотатка
-
Властивість
автор: Svitlanaflexпрацює тільки зі гнучкими елементами, тобто з тими елементами, у котрих властивістьdisplayвстановлена якflex(display: flex;абоdisplay: inline-flex). - Нотатка
-
Значення для розташування елементів у зворотньому напрямку впливають лише на їх візуальне відображення. Їхній порядок у сирцевому коді залишається незмінним.
автор: Svitlana
Синтаксис
flex-direction: row|row-reverse|column|column-reverse|initial|inherit;
Властивість flex-direction може отримувати 6 значень:
-
row -
Головна вісь спрямована так само, як і орієнтація тексту, за замовчуванням зліва направо. Якщо значення
автор: Svitlanadirзадано якrtl, то напрямок осі йде справа наліво. -
row-reverse -
Схоже на значення
автор: Svitlanarow, але міняються місцями початкова і кінцева точки і головна вісь спрямована справа наліво. Якщо значенняdirзадано якrtl, то напрямок осі йде зліва направо. -
column -
Флекс елементи відображаються у вигляді стовпчика. Стовпчик формується зверху вниз.
автор: Svitlana -
column-reverse -
Головна вісь розташовується вертикально, але змінюється положення початкової і кінцевої точок і вісь спрямована знизу вгору.
автор: Svitlana -
initial -
Встановлює цю властивість в значення без задання
автор: Svitlana -
inherit -
Успадкує значення властивості від свого батьківського елемента
автор: Svitlana
| Значення без задання: | row |
|---|---|
| Наслідує: | Ні |
| Анімується: | Ні |
| JavaScript синтаксис: | object.style.flexDirection="column-reverse" |
Переглядачі
| Переглядач | ||||||
|---|---|---|---|---|---|---|
| 29 | 22 | 9 | 12.1 | 12 | 11 |
| Переглядач | ||||
|---|---|---|---|---|
| 4.4 | 29 | 22 | 9 |
Приклади
+ запропонувати свій приклад у пісочниці
Інструмент
Показує, як властивості флекс-контейнера розставляють елементи.
Пісочниця Flexbox — окремою сторінкою, з поясненням пасток.
У розмітці елементи йдуть 1, 2, 3 — а row-reverse шикує їх від правого краю у зворотному порядку.
HTML
<div class="row">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
CSS
.row {
display: flex;
flex-direction: row-reverse;
}
.row div {
padding: 8px 16px;
border: 1px solid #0172ad;
}
Приклад роботи влативості
HTML
<div class="info">
<p>За допомогою властивості <code>flex-direction</code> ми можемо визначити напрямок головної осі гумового контейнера.</p>
<p>Ви бачите три ідентичних блоки, але для них задані різні напрямки осі: <em>row-reverse</em>, <em>column</em> й <em>column-reverse</em> відповідно.</p>
</div>
<div class="wrapper">
<ul class="block one">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<ul class="block two">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<ul class="block three">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
CSS
* {
box-sizing: border-box;
}
body {
font-family: monospace;
font-size: 15px;
line-height: 1.45;
}
.info {
padding: 6px;
}
code {
font-weight: 700;
color: #444;
border-bottom: 2px solid #666;
}
.wrapper {
display: flex;
justify-content: space-around;
}
.block {
background-color: #dedede;
padding: 0;
margin: 0;
width: 200px;
height: 200px;
list-style: none;
display: flex;
}
.block li {
text-align: center;
background-color: gold;
margin: 2px;
width: 30px;
height: 30px;
line-height: 34px;
font-weight: 700;
}
.block.one {
flex-direction: row-reverse;
}
.block.two {
flex-direction: column;
}
.block.three {
flex-direction: column-reverse;
}
HTML
<p>Цей приклад показує як працює властивість <code>flex-direction</code>. Спробуйте вимкнути/ввімкнути перемикач, щоб змінити значення властивості.</p>
<div class="inputs">
<input id="row" name="flex-direction" type="radio"/>
<label for="row">row</label>
<message for="row">Головна вісь спрямована так само, як і орієнтація тексту, за замовчуванням зліва направо. Якщо значення dir задано як rtl, то напрямок осі йде справа наліво.</message>
<input id="row-reverse" checked name="flex-direction" type="radio"/>
<label for="row-reverse">row-reverse</label>
<message for="row-reverse">Схоже на значення row, але міняються місцями початкова і кінцева точки і головна вісь спрямована справа наліво. Якщо значення dir задано як rtl, то напрямок осі йде зліва направо.</message>
<input id="column" name="flex-direction" type="radio"/>
<label for="column">column</label>
<message for="column">Флекс елементи відображаються у вигляді стовпчика. Стовпчик формується зверху вниз.</message>
<input id="column-reverse" name="flex-direction" type="radio"/>
<label for="column-reverse">column-reverse</label>
<message for="column-reverse">Головна вісь розташовується вертикально, але змінюється положення початкової і кінцевої точок і вісь спрямована знизу вгору.</message>
</div>
<div class="wm">
<p id="message"></p>
</div>
<hr>
<div id="box">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
<div class="child">5</div>
<div class="child">6</div>
<div class="child">7</div>
</div>
CSS
* {
box-sizing: border-box;
padding: 0;
}
body {
font-family: system-ui, sans-serif;
}
#box {
margin-top: 25px;
line-height: 1.45;
width: 100%;
display: flex;
background-color: gold;
padding: 4px;
}
.child {
background-color: #444;
color: #999;
text-align: center;
width: 50px;
height: 50px;
margin: 4px;
line-height: 50px;
font-weight: 700;
}
message {
display: none;
}
.wm {
min-height: 100px;
}
JS
document.querySelectorAll('.inputs input').forEach((el) => el.addEventListener('change', function () {
var messageText = document.querySelector("message[for='" + this.id + "']");
document.querySelectorAll('#message').forEach((n) => n.textContent = messageText?.textContent ?? '');
document.querySelectorAll('#box').forEach((n) => n.style.setProperty('flex-direction', this.id));
}));
Однакові правила, різний flex-direction: у row вирівнюванням по горизонталі керує justify-content, у column — align-items.
HTML
<p><code>flex-direction: row</code> — justify-content розсовує по горизонталі</p>
<div class="box row">
<div>1</div><div>2</div><div>3</div>
</div>
<p><code>flex-direction: column</code> — той самий justify-content працює вже по вертикалі</p>
<div class="box col">
<div>1</div><div>2</div><div>3</div>
</div>
CSS
body {
font-family: sans-serif;
font-size: 16px;
}
.box {
display: flex;
justify-content: space-between;
align-items: center;
height: 150px;
margin-bottom: 20px;
padding: 8px;
background: #eef6ff;
border: 1px solid #0172ad;
}
.box > div {
padding: 10px 18px;
background: gold;
border: 1px solid #333;
}
.row {
flex-direction: row;
}
.col {
flex-direction: column;
}
Значення властивості у дії
HTML
<p>Вибери потрібне значення для <code>align-direction</code>:</p>
<select id="form">
<option value="row" name="value" selected>row</option>
<option value="row-reverse" name="value">row-reverse</option>
<option value="column" name="value">column</option>
<option value="column-reverse" name="value">column-reverse</option>
</select>
<p id="text"></p>
<hr>
<div class="layout">
<header>
<h4>Simple website</h4>
</header>
<main>
<nav>
<a href="#">Item 1</a>
<a href="#">Item 2</a>
<a href="#">Item 3</a>
<a href="#">Item 4</a>
</nav>
<section id="wrapper">
<div class="child child-1">1</div>
<div class="child child-2">2</div>
<div class="child child-3">3</div>
</section>
</main>
<footer>
© 2017
</footer>
</div>
CSS
* {
box-sizing: border-box;
padding: 0;
}
body {
text-align: center;
font-family: monospace;
font-size: 17px;
line-height: 1.5;
color: #222;
}
#form {
padding: 8px 16px;
font-size: 19px;
}
header {
line-height: 75px;
text-align: center;
text-transform: uppercase;
background-color: #808080;
color: #f9f9f9;
}
main {
display: flex;
}
nav {
width: 30%;
background-color: yellow;
padding: 16px;
}
nav a {
display: block;
margin-bottom: 16px;
text-align: left;
text-decoration: none;
color: #151515;
}
#wrapper {
background-color: #eee;
display: flex;
padding: 16px;
flex: 1;
}
.child {
width: 25%;
color: #f1f1f1;
font-weight: 700;
border-radius: 4px;
background-color: #444;
border: 4px solid #666;
margin: 5px;
}
footer {
line-height: 50px;
background-color: #000;
color: #f1f1f1;
margin-top: 16px;
}
JS
var wrapper = document.getElementById('wrapper');
var form = document.getElementById('form');
var text = document.getElementById('text');
var textArray = { 'row': 'Контейнери будуть розташовані зліва направо. Якщо значення dir задано як rtl, то напрямок буде справа наліво. За замовчуванням.',
'row-reverse': 'Теж саме, що і row, але в зворотному порядку.',
'column': 'Флекс елементи відображаються у вигляді стовпчика. Стовпчик формується зверху вниз.',
'column-reverse': 'Теж саме, що і column, але знизу вверх.' };
form.onchange = function () {
for (var i = 0; i < form.options.length; i++) {if (window.CP.shouldStopExecution(0)) break;
if (form.options[i].selected == true) {
wrapper.style.flexDirection = form.options[i].value;
text.innerHTML = textArray[form.options[i].value];
}
}window.CP.exitedLoop(0);
};
//# sourceURL=pen.js
Простий приклад роботи властивості
HTML
<div class="wrapper">
<div class="gold">1</div>
<div class="red">2</div>
<div class="blue">3</div>
</div>
CSS
* {
box-sizing: border-box;
}
.wrapper {
font-family: monospace;
color: #fff;
border: 2px solid #ddd;
display: flex;
flex-direction: row-reverse;
}
.wrapper > div {
padding: 56px 16px;
width: 30%;
font-weight: 700;
font-size: 3em;
text-align: center;
}
.gold {
background-color: gold;
}
.red {
background-color: red;
}
.blue {
background-color: steelblue;
}
Коментарі
Коментарів ще немає — будьте першим!