- CSS flex-direction Property
- Definition and Usage
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- flex-direction
- Try it
- Syntax
- Values
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Reversing flex container columns and rows
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- flex — direction
- Пример
- Как понять
- Как пишется
- Возможные значения
- Подсказки
- На практике
- Алёна Батицкая советует
CSS flex-direction Property
Set the direction of the flexible items inside the element in reverse order:
Tip: More «Try it Yourself» examples below.
Definition and Usage
The flex-direction property specifies the direction of the flexible items.
Note: If the element is not a flexible item, the flex-direction property has no effect.
Default value: | row |
---|---|
Inherited: | no |
Animatable: | no. Read about animatable |
Version: | CSS3 |
JavaScript syntax: | object.style.flexDirection=»column-reverse» Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Numbers followed by -webkit- or -moz- specify the first version that worked with a prefix.
CSS Syntax
Property Values
Value | Description | Play it |
---|---|---|
row | Default value. The flexible items are displayed horizontally, as a row | Demo ❯ |
row-reverse | Same as row, but in reverse order | Demo ❯ |
column | The flexible items are displayed vertically, as a column | Demo ❯ |
column-reverse | Same as column, but in reverse order | Demo ❯ |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
More Examples
Example
Using flex-direction together with media queries to create a different layout for different screen sizes/devices:
.flex-container <
display: flex;
flex-direction: row;
>
/* Responsive layout — makes a one column layout instead of a two-column layout */
@media (max-width: 800px) .flex-container flex-direction: column;
>
>
flex-direction
Baseline is determined by this web feature being supported on the current and the previous major versions of major browsers.
The flex-direction CSS property sets how flex items are placed in the flex container defining the main axis and the direction (normal or reversed).
Try it
Note that the values row and row-reverse are affected by the directionality of the flex container. If its dir attribute is ltr , row represents the horizontal axis oriented from the left to the right, and row-reverse from the right to the left; if the dir attribute is rtl , row represents the axis oriented from the right to the left, and row-reverse from the left to the right.
Syntax
/* The direction text is laid out in a line */ flex-direction: row; /* Like , but reversed */ flex-direction: row-reverse; /* The direction in which lines of text are stacked */ flex-direction: column; /* Like , but reversed */ flex-direction: column-reverse; /* Global values */ flex-direction: inherit; flex-direction: initial; flex-direction: revert; flex-direction: revert-layer; flex-direction: unset;
Values
The following values are accepted:
The flex container’s main-axis is defined to be the same as the text direction. The main-start and main-end points are the same as the content direction.
Behaves the same as row but the main-start and main-end points are opposite to the content direction.
The flex container’s main-axis is the same as the block-axis. The main-start and main-end points are the same as the before and after points of the writing-mode.
Behaves the same as column but the main-start and main-end are opposite to the content direction.
Accessibility concerns
Using the flex-direction property with values of row-reverse or column-reverse will create a disconnect between the visual presentation of content and DOM order. This will adversely affect users experiencing low vision navigating with the aid of assistive technology such as a screen reader. If the visual (CSS) order is important, then screen reader users will not have access to the correct reading order.
Formal definition
Formal syntax
flex-direction =
row |
row-reverse |
column |
column-reverse
Examples
Reversing flex container columns and rows
HTML
h4>This is a Column-Reverseh4> div id="col-rev" class="content"> div class="box red">Adiv> div class="box lightblue">Bdiv> div class="box yellow">Cdiv> div> h4>This is a Row-Reverseh4> div id="row-rev" class="content"> div class="box red">Adiv> div class="box lightblue">Bdiv> div class="box yellow">Cdiv> div>
CSS
.content width: 200px; height: 200px; border: 1px solid #c3c3c3; display: flex; > .box width: 50px; height: 50px; > #col-rev flex-direction: column-reverse; > #row-rev flex-direction: row-reverse; > .red background-color: red; > .lightblue background-color: lightblue; > .yellow background-color: yellow; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 17, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
flex — direction
Свойство управляет направлением основной оси внутри флекс-контейнера. Поскольку поперечная ось всегда идёт перпендикулярно основной оси, то при помощи этого свойства мы управляем и её поведением тоже.
Если совсем просто, то это свойство расставляет флекс-элементы в ряд или в колонку.
Пример
Скопировать ссылку «Пример» Скопировано
В коде ниже флекс-контейнеру устанавливается горизонтальное направление основной оси. Поперечная ось при этом будет идти сверху вниз, хотя явно мы этого и не прописываем.
.container display: flex; flex-direction: row;>
.container display: flex; flex-direction: row; >
Как понять
Скопировать ссылку «Как понять» Скопировано
Одной из задач при создании флексбоксов была реализация простого механизма с расстановкой блоков в ряд или в колонку. Для этого были введены понятия осей — основной и поперечной.
И, конечно, понадобилось свойство для управления ими. Так и появилось свойство flex — direction , способное управлять обеими осями сразу.
Как пишется
Скопировать ссылку «Как пишется» Скопировано
Возможные значения
Скопировать ссылку «Возможные значения» Скопировано
- row (значение по умолчанию) — основная ось идёт горизонтально слева направо, поперечная ось идёт вертикально сверху вниз.
- row — reverse — основная ось идёт горизонтально справа налево, поперечная ось идёт вертикально сверху вниз.
- column — основная ось идёт вертикально сверху вниз, поперечная ось идёт горизонтально слева направо.
- column — reverse — основная ось идёт вертикально снизу вверх, поперечная ось идёт горизонтально слева направо.
Важный момент: на сайтах с направлением письма справа налево (RTL), например, в арабском языке, для значений row и row — reverse основная ось будет идти в обратном направлении. Для значений column и column — revers своё направление поменяет поперечная ось.
Подсказки
Скопировать ссылку «Подсказки» Скопировано
💡 Как только зададите display : flex для родителя, его дети выстроятся в ряд. Не пишите дополнительно свойство flex — direction , если не требуется менять это поведение.
Полный список свойств флексбоксов можно посмотреть в гайде по flexbox.
- Chrome 57, Поддерживается 57
- Edge 79, Поддерживается 79
- Firefox 81, Поддерживается 81
- Safari 9, Поддерживается 9
На практике
Скопировать ссылку «На практике» Скопировано
Алёна Батицкая советует
Скопировать ссылку «Алёна Батицкая советует» Скопировано
🛠 Помните, что блочные элементы по умолчанию выстраиваются друг под другом, каждый в новом ряду. Если вы написали display : flex , а потом flex — direction : column , и при этом никаких других возможностей флексбоксов не используете, то убедитесь, точно ли вам тут нужен флекс-контейнер?