Вопрос №49813 от пользователя Voltaire Aurelio в уроке «Выравнивание элементов по главной оси», курс «CSS: Основы Flex»
Если честно, я вообще не понимаю разницу между align-content и align-item .
Тут разница в том, что именно распределяется по поперечной оси. В случае align-content мы распределяем пространство между элементами (как в justify-content). А если использовать align-items, то выравниваем элементы по оси. То есть в одном случае речь о распределении пространства, а в другом о выравнивании
Можно пожалуйста прояснить один момент. Сначала я была в раздрае от того, что ничего не понимаю, потом погуглила и так и недопоняла все-таки. при flex-direction: row (по умолчанию): мы используем justify-content для выравнивания по оси х; мы используем align-items для выравнивания по оси у. Правильно ли? Если да, то логично, что если мы выставим flex-direction: column, то останутся те же свойства, только оси местами поменяются, правильно ли это мышление? Вопрос в тесте и его ответ подтверждают это:
Главная ось — ось, по которой выстраиваются элементы. Зависит от свойства flex-direction.
Но тогда в след.вопросе теста откуда ни возьмись появляется align-content, о котором в теории урока не было ни слова, ни одного примера и ответ теста таков, что:
Как можно выровнять элементы по горизонтали при flex-direction: column Правильный ответ: С помощью свойства align-content
Так мы ведь прошли в теории урока, что выравниваем мы по горизонтали, если главная ось — горизонтальная, через justify-content, и если главная ось — вертикальная, то через align-items. Вернемся к вашему ответу здесь:
В случае align-content мы распределяем пространство между элементами (как в justify-content). А если использовать align-items, то выравниваем элементы по оси.
Я окончательно запуталась, в тесте align-content выравнивает элементы по горизонтали для flex-direction: column, а тут вы ответили что разница как раз в том, что align-content распределяет пространство между элементами, а align-items выравнивает элементы по поперечной оси. Для начала я так и не пойму в чем же все-таки разница между этими понятиями. Во-вторых, в тесте вопрос, который в теории урока совсем не обсуждался. В-третьих, как все-таки используется align-content, можно примеры пожалуйста, отдельное объяснение этого момента. В-четвертых, из-за этого всего вся выстроенная в течение урока логика, что: (сокращенно) при flex-direction: главная ось >> мы используем justify-content для выравнивания по главной оси; мы используем align-items для выравнивания по поперечной оси.» вся логика рушится, или если не рушится, то объясните пожалуйста, почему мы все-таки выравниваем элементы по горизонтали для flex-direction: column через align-content. Расшифруйте для нас ответ, умоляю. Все, что нашла в интернете, только сбивает с толку и еще больше запутывает. Я обожаю Хекслет всем сердцем, но иногда он заставляет меня плакать от недопонимания ТТТТ
Поддерживаю вопрос! Читала его весь с надеждой увидеть в конце ответ. Но его почему-то нет 🙂
What’s the difference between align-content and align-items?
align-content manages the space between the lines when items wrap. align-items aligns the items relative to each other when sizes of items are different. When the size of the items are the same and there is only one line, they behave similarly.
Dec 21, 2021 at 23:12
15 Answers 15
The align-items property of flex-box aligns the items inside a flex container along the cross axis just like justify-content does along the main axis. (For the default flex-direction: row the cross axis corresponds to vertical and the main axis corresponds to horizontal. With flex-direction: column those two are interchanged respectively).
Here’s an example of how align-items:center looks:
But align-content is for multi line flexible boxes. It has no effect when items are in a single line. It aligns the whole structure according to its value. Here’s an example for align-content: space-around; :
And here’s how align-content: space-around; with align-items:center looks:
Note the 3rd box and all other boxes in first line change to vertically centered in that line.
Here are some codepen links to play with:
Here’s a super cool pen which shows and lets you play with almost everything in flexbox.
3,643 5 5 gold badges 24 24 silver badges 39 39 bronze badges
answered Jan 22, 2016 at 10:40
17k 11 11 gold badges 79 79 silver badges 102 102 bronze badges
Note that the align-* properties can also shift flex items horizontally. It depends on the flex-direction . stackoverflow.com/q/32551291/3597276
Jan 29, 2016 at 17:09
> «But align-content is for multi line flexible boxes. It has no effect when items are in a single line» — this appears to not be true, or not be honoured, in latest Firefox (May 2020). Instead, if there’s a single flex-line (all content fits within less than the main-axis length) which is less than full height (cross-axis size is less than full available), then align-content if set will obliterate align-items. This makes sense: it applies to ANY lines it finds?
May 2, 2020 at 22:07
React native layout arrangement is a joke. The property terms are so misleading! Its just my personal opinion after dealing with much, much simpler layout android SDK offers
Oct 26, 2022 at 16:17
You said that align-items is like justify-content, but in the perpendicular axis. Then why it don’t have values like “space-evenly”? Also, You said align-content only works in multi-line flex but for me, it’s also working on single line flex. Here’s the pen: codepen.io/Utsav_0/pen/oNMKZXV
Feb 11 at 2:58
It will take you 10-20 minutes and at level 21 you will find the answer to your question.
align-content determines the spacing between lines
align-items determines how the items as a whole are aligned within the container.
When there is only one line, align-content has no effect
answered Aug 16, 2017 at 12:06
Alireza Fattahi Alireza Fattahi
42.9k 14 14 gold badges 125 125 silver badges 173 173 bronze badges
Indeed, I did find the froggy example really useful. Learned a lot from it.
Feb 18, 2019 at 5:44
Actually, align-content does have effect for a single line content, too, if the container has non-shrink-wrap height (that is, container is higher than any of the child items). The align-items positions each child relative to the line of content and align-content positions each line of content relative to the container. And the names are «align» and «justify» because the real orientation depends on flex-flow . I’d prefer «parallel» and «orthogonal» instead.
Mar 19, 2021 at 8:42
@MikkoRantalainen: I don’t observe any effect of align-content on single line/column flex content. Also, MDN disagrees with you (developer.mozilla.org/en-US/docs/Web/CSS/align-content).
Oct 11, 2021 at 10:23
@wortwart See demo at jsfiddle.net/n2ruogLt – note how row with letters a,b,c,d end up at the end of the container even when it doesn’t have align-content .
Oct 11, 2021 at 14:43
@Spikatrix I couldnt finish level 24. Certain things didnt seem to have effect anymore like changing justify-content
Jul 23, 2022 at 13:45
First, align-items is for items in a single row. So for a single row of elements on main axis, align-items will align these items respective of each other and it will start with fresh perspective from the next row.
Now, align-content doesn’t interfere with items in a row but with rows itself. Hence, align-content will try to align rows with respect to each other and flex container.
5,088 5 5 gold badges 30 30 silver badges 41 41 bronze badges
answered May 29, 2016 at 10:46
Uday Hiwarale Uday Hiwarale
4,048 6 6 gold badges 46 46 silver badges 50 50 bronze badges
So for a flex-direction of row, does align content only do something if the flexbox has a height set and therefore doesn’t just use the child element’s height leaving no room to add space between/around the rows?
Feb 22 at 17:31
I had the same confusion. After some tinkering based on many of the answers above, I can finally see the differences. In my humble opinion, the distinction is best demonstrated with a flex container that satisfies the following two conditions:
- The flex container itself has a height constraint (e.g., min-height: 60rem ) and thus can become too tall for its content
- The child items enclosed in the container have uneven heights
Condition 1 helps me understand what content means relative to its parent container. When the content is flush with the container, we will not be able to see any positioning effects coming from align-content . It is only when we have extra space along the cross axis, we start to see its effect: It aligns the content relative to the boundaries of the parent container.
Condition 2 helps me visualize the effects of align-items : it aligns items relative to each other.
Here is a code example. Raw materials come from Wes Bos’ CSS Grid tutorial (21. Flexbox vs. CSS Grid)
Short Longerrrrrrrrrrrrrr This is Many Words Lorem, ipsum. 10 Snickers Wes Is Cool Short
- Example CSS:
.flex-container < display: flex; /*dictates a min-height*/ min-height: 60rem; flex-flow: row wrap; border: 5px solid white; justify-content: center; align-items: center; align-content: flex-start; >#tall < /*intentionally made tall*/ min-height: 30rem; >.item
Example 1: Let’s narrow the viewport so that the content is flush with the container. This is when align-content: flex-start; has no effects since the entire content block is tightly fit inside the container (no extra room for repositioning!)
Also, note the 2nd row—see how the items are center aligned among themselves.
Example 2: As we widen the viewport, we no longer have enough content to fill the entire container. Now we start to see the effects of align-content: flex-start; —it aligns the content relative to the top edge of the container.
These examples are based on flexbox, but the same principles are applicable to CSS grid. Hope this helps 🙂
answered Dec 26, 2018 at 23:00
3,098 1 1 gold badge 20 20 silver badges 18 18 bronze badges
Shoutout to wesbos ? 😛
Aug 27, 2022 at 6:36
Fantastic explanation. Condition 1 and Condition 2 were what was missing from most of the other explanations here. Thanks!
Jun 13 at 11:24
The effect of both align-items and align-content is along the cross-axis.
Let say if flex-direction is row then the main axis is Left to Right and if flex-direction is column then the main axis is from top to bottom .
So In the below examples, we gonna assume that flex-direction is row i.e. main axis is from Left to Right and cross-axis is from top to bottom.
align-content only works if there is flex-wrap: wrap and if there is more than one flex-line in container.
align-content has higher priority than align-items if there are multiple flex-line.
What is flex-line?
Each row or column of flex items in a flex container is a flex line. Multiple lines occur when there is not enough space in a container and flex-items would take the next line(in flex-direction: row; ) to fit in. In flex-direction: column it will add flex items to next line.
By default, the flex is a flexible container i.e. it can accommodate any number of elements unless we have specified flex-wrap: wrap . Without wrap, flex-items will overflow the container(if flex-direction is row ).
align-content example
.container < border: 5px solid #000; height: 100vh; display: flex; flex-wrap: wrap; align-content: flex-end; >.box < height:100px; font-size: 2rem; width: 33.33%; >.box1 < background: purple; >.box2 < background: #ff8c00; >.box3 < background: lime; >.box4 < background: #008080; >.box5
box 1 box 2 box 3 box 4 box 5
In the above example, If there would have been flex-wrap: no-wrap then align-content doesn’t affect our layout.
align-items example
The align-items property determines how flex items are positioned within a flex line, along the cross-axis.
.container < border: 5px solid #000; height: 100vh; display: flex; flex-wrap: wrap; align-items: flex-end; >.box < height:100px; font-size: 2rem; width: 33.33%; >.box1 < background: purple; >.box2 < background: #ff8c00; >.box3 < background: lime; >.box4 < background: #008080; >.box5
box 1 box 2 box 3 box 4 box 5
If align-content and align-items are declared on a container with properties flex-wrap: wrap and if there are more than flex-line then align-content property has higher priority than align-items .
align-content and align-items priority example
.container < border: 5px solid #000; height: 100vh; display: flex; flex-wrap: wrap; align-content: flex-end; align-items: flex-start; >.box < height:100px; font-size: 2rem; width: 33.33%; >.box1 < background: purple; >.box2 < background: #ff8c00; >.box3 < background: lime; >.box4 < background: #008080; >.box5
box 1 box 2 box 3 box 4 box 5
answered Mar 23, 2021 at 5:32
24.7k 6 6 gold badges 26 26 silver badges 42 42 bronze badges
Well I have examined them on my browser.
align-content can change a line’s height for row direction or width for column when it’s value is stretch, or add empty space between or around the lines for space-between , space-around , flex-start , flex-end values .
align-items can change items height or position inside the line’s area. When items are not wrapped they have only one line which it’s area is always stretched to the flex-box area (even if the items overflow), and align-content has no effect on a single line. So it has no effect on items that are not wrapped and only align-items can change items position or stretch them when all of them are on a single line.
However, if they are wrapped you have multiple lines and items inside each line. And if all items of each line have the same height (for row direction) that line’s height will be equal to those items height and you don’t see any effect by changing align-items value.
So if you want to affect items by align-items when your items are wrapped and have the same height (for row direction) first you have to use align-content with stretch value in order to expand the lines area.
Выравнивание элементов. align-items и align-self¶
Свойство align-items также выравнивает элементы, но уже по поперечной оси (cross axis) (при расположении в виде строки по вертикали, при расположении в виде столбца — по горизонтали). Это свойство может принимать следующие значения:
- stretch : значение по умолчанию, при котором flex-элементы растягиваются по всей высоте (при расположении в строку) или по всей ширине (при расположении в столбик) flex-контейнера
- flex-start : элементы выравниваются по верхнему краю (при расположении в строку) или по левому краю (при расположении в столбик) flex-контейнера
- flex-end : элементы выравниваются по нижнему краю (при расположении в строку) или по правому краю (при расположении в столбик) flex-контейнера
- center : элементы выравниваются по центру flex-контейнера
- baseline : элементы выравниваются в соответствии со своей базовой линией
Выравнивание при расположении в строку:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
html> head> meta charset="utf-8" /> title>Flexbox в CSS3title> style> .flex-container display: flex; border: 1px #ccc solid; height: 5em; > .flex-start align-items: flex-start; > .flex-end align-items: flex-end; > .center align-items: center; > .baseline align-items: baseline; > .flex-item text-align: center; font-size: 1em; padding: 1.2em; color: white; > .largest-item padding-top: 2em; > .color1 background-color: #675ba7; > .color2 background-color: #9bc850; > .color3 background-color: #a62e5c; > .color4 background-color: #2a9fbc; > style> head> body> h3>Flex-starth3> div class="flex-container flex-start"> div class="flex-item color1">Flex Item 1div> div class="flex-item color2">Flex Item 2div> div class="flex-item color3">Flex Item 3div> div class="flex-item color4">Flex Item 4div> div> h3>Flex-endh3> div class="flex-container flex-end"> div class="flex-item color1">Flex Item 1div> div class="flex-item color2">Flex Item 2div> div class="flex-item color3">Flex Item 3div> div class="flex-item color4">Flex Item 4div> div> h3>Centerh3> div class="flex-container center"> div class="flex-item color1">Flex Item 1div> div class="flex-item color2">Flex Item 2div> div class="flex-item color3">Flex Item 3div> div class="flex-item color4">Flex Item 4div> div> h3>Baselineh3> div class="flex-container baseline"> div class="flex-item color1">Flex Item 1div> div class="flex-item color2 largest-item"> Flex Item 2 div> div class="flex-item color3">Flex Item 3div> div class="flex-item color4">Flex Item 4div> div> body> html>
Аналогично свойство работает при расположении в столбик. Например, изменим стили flex-контейнера следующим образом:
1 2 3 4 5 6
.flex-container display: flex; border: 1px #ccc solid; flex-direction: column; width: 12em; >
Свойство align-self¶
Свойство align-self позволяет переопределить значение свойства align-items для одного элемента. Оно может принимать все те же значения плюс значение auto :
- auto : значение по умолчанию, при котором элемент получает значение от свойства align-items , которое определено в flex-контейнере. Если в контейнере такой стиль не определен, то применяется значение stretch .
- stretch
- flex-start
- flex-end
- center
- baseline
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
html> head> meta charset="utf-8" /> title>Flexbox в CSS3title> style> .flex-container display: flex; border: 1px #ccc solid; justify-content: space-between; align-items: stretch; height: 12em; > .flex-item text-align: center; font-size: 1em; padding: 1.2em; color: white; > .item1 background-color: #675ba7; align-self: center; > .item2 background-color: #9bc850; align-self: flex-start; > .item3 background-color: #a62e5c; align-self: flex-end; > .item4 background-color: #2a9fbc; align-self: center; > style> head> body> h3>Align-selfh3> div class="flex-container"> div class="flex-item item1">Flex Item 1div> div class="flex-item item2">Flex Item 2div> div class="flex-item item3">Flex Item 3div> div class="flex-item item4">Flex Item 4div> div> body> html>
Здесь для flex-контейнера задано растяжение по высоте с помощью значения align-items: stretch; . Однако каждый из элементов переопределяет это поведение:
Флексы для начинающих
Flexbox — инструмент построения крупных сеток и микросеток.
Чтобы превратить блок во флекс-контейнер, ему задают свойство display: flex . Непосредственные потомки такого контейнера — флекс-элементы — становятся гибкими. Они легко сжимаются или растягиваются, меняют порядок, поддаются выравниванию по главной и поперечной осям.
Благодаря таким свойствам мы можем создавать на флексах меню сайта, раздел с карточками товаров, пагинацию или любые другие блоки, в которых нужно предусмотреть переполнение контентом. При правильном использовании Flexbox вы получите отзывчивый сайт, который легко адаптируется к различным размерам экрана и устройствам.
Главная и поперечная оси
Элементы флекс-контейнера выравниваются вдоль двух осей: главной и поперечной.
Главная ось указывает направление потока флекс-элементов. По умолчанию он течёт по горизонтали слева направо, от начала к концу оси:
Направлением главной оси можно управлять, меняя значения свойства flex-direction :
- flex-direction: row — ось направлена слева направо, элементы располагаются в ряд. Это значение по умолчанию.
- flex-direction: row-reverse — элементы идут в обратном направлении — справа налево.
- flex-direction: column — элементы располагаются в столбец сверху вниз.
- flex-direction: column-reverse — элементы идут снизу вверх.
Чаще всего используется значение по умолчанию — row , чуть реже — column . x-reverse применяют редко.
Поперечная ось всегда находится под углом 90 градусов к главной. Если главная ось горизонтальна, поперечная идёт сверху вниз, а если главная вертикальна, то поперечная направлена слева направо.
justify-content
Флекс-элементами можно управлять, меняя их положение относительно каждой оси. CSS-свойство justify-content распределяет элементы по главной оси. Оно принимает следующие значения:
- flex-start — элементы стоят в начале оси.
- flex-end — элементы стоят в конце оси.
- center — элементы по центру оси.
- space-between — элементы равномерно распределены вдоль главной оси, при этом первый элемент располагается в начале, а последний — в конце. Между крайними элементами и флекс-контейнером отступа нет.
- space-around — элементы равномерно распределены вдоль оси. Расстояние между крайними элементами и флекс-контейнером равно половине отступа между соседними флекс-элементами.
- space-evenly — элементы равномерно размещены вдоль оси. Отступы между соседними элементами и краями флекс-контейнера равны.
align-items
За выравнивание элементов по поперечной оси отвечает свойство align-items . По умолчанию у него значение stretch , то есть элементы растягиваются вдоль всей оси.
- flex-start — элементы идут в начале оси;
- flex-end — элементы идут в конце оси;
- center — элементы в центре оси;
- baseline — элементы размещены по базовой линии.
Базовая линия — невидимая линия, которая проходит по нижней части букв.
Порой в макете отдельные элементы располагаются выше или ниже, правее или левее. На такие случаи во флексах есть свойство align-self . Оно выравнивает отдельный элемент по поперечной оси.
Значения align-self такие же, как у align-items.
align-content
Вдоль поперечной оси можно выравнивать не только элементы, но и ряды флекс-элементов — это делается с помощью свойства align-content .
align-content немного похож на свойства justify-content и align-items . От первого он взял значения:
- flex-start
- flex-end
- center
- space-between
- space-around
- space-evenly
От align-items достались свойства: stretch и baseline .
С align-content мы можем расположить ряды элементов более гибко — например, задав одинаковые расстояния между ними или растянув на всю возможную высоту.
Отличие align-content от align-items
align-items выравнивает элементы внутри флекс-контейнера, а align-content — ряды.
По умолчанию у align-content значение stretch — то есть ряды флекс-элементов растягиваются, и свободное пространство делится между ними пополам. В таких случаях отображение зависит от значения align-items . Если это тоже stretch , то элементы в строке растянутся на всю высоту. Если нет — элементы сожмутся до размеров содержимого и выровняются согласно значению align-items .
Когда align-content задано другое значение (не stretch ), оно перекрывает значения align-items и align-self . Например, здесь ряды элементов окажутся в конце поперечной оси:
flex-wrap
В коде выше есть свойство flex-wrap — оно отвечает за перенос строк во флекс-контейнере. По умолчанию у свойства стоит значение no-wrap , то есть перенос запрещён. При добавлении новых элементов все элементы станут сжиматься до минимально возможной ширины — даже если явно указано значение width . Когда элементы перестанут помещаться в контейнере, то выйдут за его пределы.
Чтобы элементы при заполнении ряда переносились на новый, нужно указать flex-wrap: wrap . Наглядный пример — гифка в начале статьи.
Ещё без переноса рядов не работает свойство align-content . Например, в таком случае элементы выровняются по началу поперечной оси.
Игры и курсы для практики
Флексы — очень гибкий инструмент, с его помощью можно создавать сложные микросетки и даже менять элементы местами. Основу теории вы теперь знаете — дальше дело за закреплением материала и углублением знаний.
Где практиковаться и что изучить:
- Flexbox froggy — игра на русском языке, где вы с помощью флексов размещаете лягушат на кувшинках.
- Flexbox Defense — англоязычная игра в стиле Tower Defense. Вы на флексах располагаете башни, чтобы защититься от врагов.
- Навык «Построение сеток на флексах по макету». Изучаете 50 страниц углублённой теории о flexbox и выполняете задания — строите сетки для сайта. В навыке 10 кейсов разной сложности с макетом в формате Figma и готовым решением.
- Курс «HTML и CSS. Профессиональная вёрстка сайтов». Научитесь верстать сайты и писать для них стили. Изучите не только флексы, но и гриды — ещё один современный механизм построения сеток.
Материалы по теме
- Примеры использования флексов
- Когда использовать флексы, а когда гриды
- Как сверстать макет
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.