Синтаксис
/* Positional alignment */ align-content: center; /* Pack items around the center */ align-content: start; /* Pack items from the start */ align-content: end; /* Pack items from the end */ align-content: flex-start; /* Pack flex items from the start */ align-content: flex-end; /* Pack flex items from the end */ align-content: left; /* Pack items from the left */ align-content: right; /* Pack items from the right */ /* Baseline alignment */ align-content: baseline; align-content: first baseline; align-content: last baseline; /* Distributed alignment */ align-content: space-between; /* Distribute items evenly The first item is flush with the start, the last is flush with the end */ align-content: space-around; /* Distribute items evenly Items have a half-size space on either end */ align-content: space-evenly; /* Distribute items evenly Items have equal space around them */ align-content: stretch; /* Distribute items evenly Stretch 'auto'-sized items to fit the container */ /* Overflow alignment */ align-content: safe center; align-content: unsafe center; /* Global values */ align-content: inherit; align-content: initial; align-content: unset;
Значения
Значение | Положение | Описание |
---|---|---|
flex-start |
![]() |
Строки располагаются в начале поперечной оси. Каждая следующая строка идёт вровень с предыдущей. |
center |
![]() |
Строки располагаются по центру контейнера. |
flex-end |
![]() |
Строки располагаются начиная с конца поперечной оси. Каждая предыдущая строка идёт вровень со следующей. |
space-between |
![]() |
Строки равномерно распределяются в контейнере и расстояние между ними одинаково. |
space-around
|
![]() |
Строки равномерно распределяются таким образом, чтобы пространство между двумя соседними строками было одинаковым. Пустое пространство перед первой строкой и после последней строки равно половине пространства между двумя соседними строками. |
stretch |
![]() |
Строки равномерно растягиваются, заполняя свободное пространство. |
Примеры
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>align-content</title> <style> .flex-container { width: 70px; height: 240px; border: 1px solid #333; padding: 10px; display: flex; flex-wrap: wrap; align-content: center; } .flex-container div { width: 70px; height: 70px; border-radius: 50%; } .red { background: red; } .yellow { background: yellow; } .green { background: green; } </style> </head> <body> <div class="flex-container"> <div class="red"></div> <div class="yellow"></div> <div class="green"></div> </div> </body> </html>
Примечание
Safari до версии 9 поддерживает свойство -webkit-align-content
.
xsltdev.ru
Поддержка браузерами
11.0+ | 28.0+ | 21.0+ | 12.1+ | 9.0+ |
Описание
CSS свойство align-content указывает, каким образом будут выравниваться flex-элементы по вертикали внутри flex-контейнера, если разрешён перенос элементов и строк с элементами две или больше.
Примечание: для выравнивания flex-элементов по горизонтали используйте свойство justify-content.
Значение по умолчанию: | stretch |
---|---|
Применяется: | к многострочным flex-контейнерам |
Анимируется: | нет |
Наследуется: | нет |
Версия: | CSS3 |
Синтаксис JavaScript: | object.style.alignContent=»center»; |
Синтаксис
align-content: stretch|center|flex-start|flex-end|space-between|space-around;
Значения свойства
Значение | Описание |
---|---|
stretch | Значение по умолчанию. Если у flex-элементов не задана высота, то они растягиваются на всю высоту контейнера так, чтобы каждая строка имела одинаковую высоту. |
center | flex-элементы располагаются точно по центру flex-контейнера, то есть снизу и сверху от элементов расстояние до границ контейнера будет одинаковым.
Примечание: если flex-элементы занимают больше вертикального пространства, чем высота контейнера, то элементы сместятся так, чтобы переполнение было одинаковым с обоих сторон контейнера. |
flex-start | flex-элементы выравниваются по левому верхнему углу контейнера. |
flex-end | flex-элементы выравниваются по левому нижнему углу контейнера. |
space-between | Строки с flex-элементами равномерно распределяются по вертикали так, чтобы между каждой парой соседних строк расстояние было одинаковым. Первая строка прилегает своей верхней границей к верхней границе контейнера, а последняя строка прилегает своей нижней границей к нижней границе контейнера.
Примечание: если flex-элементы занимают больше вертикального пространства, чем высота контейнера, то данное значение будет соответствовать значению flex-start. |
space-around | Строки с flex-элементы равномерно распределяются по вертикали так, чтобы между каждой парой соседних строк расстояние было одинаковым. Пустое пространство перед первой и после последней строки равно половине расстояния между каждой парой соседних строк.
Примечание: если flex-элементы занимают больше вертикального пространства, чем высота контейнера, то данное значение будет соответствовать значению center. |
Пример
puzzleweb.ru
Синтаксис
/* Basic positional alignment */ /* align-content does not take left and right values */ align-content: center; /* Pack items around the center */ align-content: start; /* Pack items from the start */ align-content: end; /* Pack items from the end */ align-content: flex-start; /* Pack flex items from the start */ align-content: flex-end; /* Pack flex items from the end */ /* Normal alignment */ align-content: normal; /* Baseline alignment */ align-content: baseline; align-content: first baseline; align-content: last baseline; /* Distributed alignment */ align-content: s.
er; /* Global values */ align-content: inherit; align-content: initial; align-content: unset;
Значения
-
start
- Элементы упаковываются друг за другом в направлении к краю начала контейнера выравнивания по поперечной оси.
-
end
- Элементы упаковываются друг за другом в направлении к краю контейнера выравнивания по поперечной оси.
-
flex-start
- Элементы упаковываются заподлицо друг к другу к краю контейнера выравнивания в зависимости от стороны поперечного начала гибкого контейнера.
Это относится только к элементам гибкого макета. Для элементов, которые не являются дочерними элементами гибкого контейнера, это значение обрабатывается какstart
. -
flex-end
- Элементы упаковываются заподлицо друг к другу к краю контейнера выравнивания в зависимости от стороны кросс-контейнера гибкого контейнера.
Это относится только к элементам гибкого макета. Для элементов, которые не являются дочерними элементами гибкого контейнера, это значение обрабатывается какend
. -
center
- Элементы упаковываются друг за другом в центр контейнера для выравнивания вдоль поперечной оси.
-
normal
- Элементы упакованы в позицию по умолчанию, как если бы не было установлено значение
align-content
. -
baseline
first baseline
last baseline
» style=»height: 110px; width: 410px;»/>
- Определяет участие в выравнивании по первой или последней базовой линии: выравнивает базовую линию выравнивания первой или последней базовой линии коробки с соответствующей базовой линией в общем первом или последнем базовом наборе всех ящиков в своей группе совместного использования базовой линии.
Исходное выравнивание дляfirst baseline
start
, дляlast baseline
—end
. -
space-between
- Элементы равномерно распределены внутри контейнера выравнивания вдоль поперечной оси. Расстояние между каждой парой смежных элементов одинаково. Первый элемент заподлицо с краем основного запуска, а последний элемент заподлицо с краем основного конца.
-
space-around
- Элементы равномерно распределены внутри контейнера выравнивания вдоль поперечной оси. Расстояние между каждой парой смежных элементов одинаково. Пустое пространство перед первым и после последнего элемента равно половине пространства между каждой парой смежных элементов.
-
space-evenly
- Элементы равномерно распределены внутри контейнера выравнивания вдоль поперечной оси. Расстояние между каждой парой смежных элементов, краем основного начала и первым элементом, а также краем основного конца и последним элементом — все одинаково.
-
stretch
- Если объединенный размер элементов вдоль поперечной оси меньше размера контейнера выравнивания, любые объекты с
auto
определением имеют размер, увеличиваемый одинаково (не пропорционально), при этом сохраняя ограничения, налагаемыеmax-height
/max-width
(или эквивалентной функциональности), так что комбинированный размер точно заполняет контейнер выравнивания вдоль поперечной оси. -
safe
- Если размер элемента переполняет контейнер выравнивания, элемент выравнивается, как если бы режим выравнивания
start
. -
unsafe
- Независимо от относительных размеров предмета и контейнера выравнивания, данное значение выравнивания соблюдается.
Формальный синтаксис
flex-start | flex-end | center | space-between | space-around | space-evenly | stretch
пример
CSS
#container { height:200px; width: 240px; align-content: center; /* Can be changed in the live sample */ background-color: #8c8c8c; } .flex { display: flex; flex-wrap: wrap; } .grid { display: grid; grid-template-columns: repeat(auto-fill, 50px); } div > div { box-sizing: border-box; border: 2px solid #8c8c8c; width: 50px; display: flex; align-items: center; justify-content: center; } #item1 { background-color: #8cffa0; min-height: 30px; } #item2 { background-color: #a0c8ff; min-height: 50px; } #item3 { background-color: #ffa08c; min-height: 40px; } #item4 { background-color: #ffff8c; min-height: 60px; } #item5 { background-color: #ff8cff; min-height: 70px; } #item6 { background-color: #8cffff; min-height: 50px; font-size: 30px; } select { font-size: 16px; } .row { margin-top: 10px; }
HTML
<div id="container" class="flex"> <div id="item1">1</div> <div id="item2">2</div> <div id="item3">3</div> <div id="item4">4</div> <div id="item5">5</div> <div id="item6">6</div> </div> <div class="row"> <label for="display">display: </label> <select .
<option value="center" selected>center</option> <option value="space-between">space-between</option> <option value="space-around">space-around</option> <option value="space-evenly">space-evenly</option> <option value="start">start</option> <option value="end">end</option> <option value="left">left</option> <option value="right">right</option> <option value="baseline">baseline</option> <option value="first baseline">first baseline</option> <option value="last baseline">last baseline</option> <option value="safe center">safe center</option> <option value="unsafe center">unsafe center</option> <option value="safe right">safe right</option> <option value="unsafe right">unsafe right</option> <option value="safe end">safe end</option> <option value="unsafe end">unsafe end</option> <option value="safe flex-end">safe flex-end</option> <option value="unsafe flex-end">unsafe flex-end</option> </select> </div>
результат
code-examples.net
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)
- Example HTML:
<div class="flex-container"> <div class="item">Short</div> <div class="item">Longerrrrrrrrrrrrrr</div> <div class="item">?</div> <div class="item" id="tall">This is Many Words</div> <div class="item">Lorem, ipsum.</div> <div class="item">10</div> <div class="item">Snickers</div> <div class="item">Wes Is Cool</div> <div class="item">Short</div> </div>
- 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 { margin: 10px; max-height: 10rem; }
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 🙂
stackoverflow.com
Определение и применение
CSS свойство align-content определяет как браузер распределяет пространство между и вокруг флекс элементов вдоль поперечной оси контейнера (вертикально), или производит выравнивание всего макета сетки по оси столбца grid-контейнера.
Для того, чтобы определить как браузер распределяет пространство между и вокруг флекс элементов вдоль главной оси контейнера (горизонтально), или производит выравнивание всего макета сетки по оси строки grid-контейнера, вы можете воспользоваться свойством justify-content.
При работе с флекс элементами обратите внимание на то, что свойство align-content возможно применить только к многострочным флекс контейнерам (flex-wrap
, или flex-flow
со значениями wrap | wrap-reverse).
Если элемент не является флекс элементом, или элементом сетки макета (не находится внутри родительского элемента, который является блочным, или строчным флекс, или grid-контейнером), то свойство align-content не окажет на такой элемент никакого эффекта.
Более подробную информацию о работе с флекс элементами вы можете получить в статье учебника CSS «Верстка по Flexbox (работа с контейнерами)».
Схематичное отображение работы свойства align-content отображено на следующем изображении:
* — для элементов сетки макета (grid-элементы) допускается использование сокращенных значений start и end, для флекс элементов необходимо использовать полные значения flex-start и flex-end.
Поддержка браузерами
CSS синтаксис:
/* flex-контейнеры */ align-content: "stretch | flex-start | flex-end | center | space-between | space-around | space-evenly | initial | inherit"; /* grid-контейнеры */ align-content: "stretch | start | end | center | space-between | space-around | space-evenly | initial | inherit";
JavaScript синтаксис:
object.style.alignContent = "space-between"
Значения свойства
Значение | Описание |
---|---|
stretch | Строки внутри контейнера равномерно растягиваются, заполняя свободное пространство (изменяет размер элементов сетки, или флекс элементов, чтобы элементы заполнили всю высоту контейнера). Это значение по умолчанию. |
flex-start | Строки внутри контейнера располагаются в начале поперечной оси флекс контейнера, или начального края сетки grid-контейнера. Для элементов сетки макета (grid-элементы) допускается использование сокращенного значения start, для флекс элементов необходимо использовать полное значение flex-start |
flex-end | Строки внутри контейнера располагаются в конце поперечной оси флекс контейнера, или по краю сетки grid-контейнера. Для элементов сетки макета (grid-элементы) допускается использование сокращенного значения end, для флекс элементов необходимо использовать полное значение flex-end. |
center | Строки внутри контейнера располагаются по его центру. |
space-between | Строки внутри контейнера равномерно распределяются, при этом первая строка позиционируются в начале поперечной оси, а последняя строка позиционируется с конца поперечной оси. |
space-around |
Строки внутри контейнера равномерно распределяются, при этом пространство между двумя соседними строками одинаково, а пустое пространство перед первой строкой и после последней строки равно половине от пространства между соседними строками: |
space-evenly |
Размещает четный промежуток между каждой строкой, включая верхний и нижний край контейнера: |
initial | Устанавливает свойство в значение по умолчанию. |
inherit | Указывает, что значение наследуется от родительского элемента. |
basicweb.ru
Свойство align-content устанавливает тип выравнивания строк флекс-элементов по вертикали внутри флекс-контейнера, позволяя управлять свободным пространством.
Свойство align-content работает только в случае, если разрешен перенос строк и указано направление flex-flow: row/row-reverse/column/column-reverse wrap/wrap-reverse; и высота flex-контейнера.
CSS синтаксис
Возможные значения
Значение | Описание |
---|---|
stretch | Значение по умолчанию. Строки флекс-элементов равномерно растягиваются, заполняя все доступное пространство. |
center | Строки флекс-элементов выравниваются по высоте по середине контейнера относительно его левого края. |
flex-start | Строки флекс-элементов выравниваются по левому краю контейнера относительно его верхнего края. |
flex-end | Строки флекс-элементов выравниваются по левому краю контейнера относительно его нижнего края. |
space-between | Строки флекс-элементов выравниваются по высоте по середине контейнера относительно его левого края. Свободное пространство распределяется между ними. Первый ряд флекс-элементов прижимается к началу контейнера, последний ряд — к нижнему краю. |
space-around | Строки флекс-элементов равномерно распределяются по высоте, свободное пространство добавляется сверху и снизу строки. |
inherit | Значение наследуется от родительского элемента. |
initial | Устанавливает значение по умолчанию. |
Пример
Упаковываем строки в середину флекс-контейнера
div { width: 70px; height: 300px; border: 1px solid #c3c3c3; display: -webkit-flex; display: flex; -webkit-flex-wrap: wrap; flex-wrap: wrap; -webkit-align-content: center; align-content: center; }
msiter.ru
Syntax
/* Basic positional alignment */ /* align-content does not take left and right values */ align-content: center; /* Pack items around the center */ align-content: start; /* Pack items from the start */ align-content: end; /* Pack items from the end */ align-content: flex-start; /* Pack flex items from the start */ align-content: flex-end; /* Pack flex items from the end */ /* Normal alignment */ align-content: normal; /* Baseline alignment */ align-content: baseline; align-content: first baseline; align-content: last baseline; /* Distributed alignment */ align-content: space-between; /* Distribute items evenly The first item is flush with the start, the last is flush with the end */ align-content: space-around; /* Distribute items evenly Items have a half-size space on either end */ align-content: space-evenly; /* Distribute items evenly Items have equal space around them */ align-content: stretch; /* Distribute items evenly Stretch 'auto'-sized items to fit the container */ /* Overflow alignment */ align-content: safe center; align-content: unsafe center; /* Global values */ align-content: inherit; align-content: initial; align-content: unset;
Values
start
- The items are packed flush to each other toward the start edge of the alignment container in the cross axis.
end
- The items are packed flush to each other toward the end edge of the alignment container in the cross axis.
flex-start
- The items are packed flush to each other toward the edge of the alignment container depending on the flex container’s cross-start side.
This only applies to flex layout items. For items that are not children of a flex container, this value is treated likestart
. flex-end
- The items are packed flush to each other toward the edge of the alignment container depending on the flex container’s cross-end side.
This only applies to flex layout items. For items that are not children of a flex container, this value is treated likeend
. center
- The items are packed flush to each other toward the center of the alignment container along the cross axis.
normal
- The items are packed in their default position as if no
align-content
value was set. baseline
first baseline
last baseline
- Specifies participation in first- or last-baseline alignment: aligns the alignment baseline of the box’s first or last baseline set with the corresponding baseline in the shared first or last baseline set of all the boxes in its baseline-sharing group.
The fallback alignment forfirst baseline
isstart
, the one forlast baseline
isend
. space-between
- The items are evenly distributed within the alignment container along the cross axis. The spacing between each pair of adjacent items is the same. The first item is flush with the main-start edge, and the last item is flush with the main-end edge.
space-around
- The items are evenly distributed within the alignment container along the cross axis. The spacing between each pair of adjacent items is the same. The empty space before the first and after the last item equals half of the space between each pair of adjacent items.
space-evenly
- The items are evenly distributed within the alignment container along the cross axis. The spacing between each pair of adjacent items, the main-start edge and the first item, and the main-end edge and the last item, are all exactly the same.
stretch
- If the combined size of the items along the cross axis is less than the size of the alignment container, any
auto
-sized items have their size increased equally (not proportionally), while still respecting the constraints imposed bymax-height
/max-width
(or equivalent functionality), so that the combined size exactly fills the alignment container along the cross axis. safe
- Used alongside an alignment keyword. If the chosen keyword means that the item overflows the alignment container causing data loss, the item is instead aligned as if the alignment mode were
start
. unsafe
- Used alongside an alignment keyword. Regardless of the relative sizes of the item and alignment container and whether overflow which causes data loss might happen, the given alignment value is honored.
Formal syntax
normal | <baseline-position> | <content-distribution> | <overflow-position>? <content-position>where
<baseline-position> = [ first | last ]? baseline
<content-distribution> = space-between | space-around | space-evenly | stretch
<overflow-position> = unsafe | safe
<content-position> = center | start | end | flex-start | flex-end
Example
CSS
#container { height:200px; width: 240px; align-content: center; /* Can be changed in the live sample */ background-color: #8c8c8c; } .flex { display: flex; flex-wrap: wrap; } .grid { display: grid; grid-template-columns: repeat(auto-fill, 50px); } div > div { box-sizing: border-box; border: 2px solid #8c8c8c; width: 50px; display: flex; align-items: center; justify-content: center; } #item1 { background-color: #8cffa0; min-height: 30px; } #item2 { background-color: #a0c8ff; min-height: 50px; } #item3 { background-color: #ffa08c; min-height: 40px; } #item4 { background-color: #ffff8c; min-height: 60px; } #item5 { background-color: #ff8cff; min-height: 70px; } #item6 { background-color: #8cffff; min-height: 50px; font-size: 30px; } select { font-size: 16px; } .row { margin-top: 10px; }
HTML
<div id="container" class="flex"> <div id="item1">1</div> <div id="item2">2</div> <div id="item3">3</div> <div id="item4">4</div> <div id="item5">5</div> <div id="item6">6</div> </div> <div class="row"> <label for="display">display: </label> <select id="display"> <option value="flex">flex</option> <option value="grid">grid</option> </select> </div> <div class="row"> <label for="values">align-content: </label> <select id="values"> <option value="normal">normal</option> <option value="stretch">stretch</option> <option value="flex-start">flex-start</option> <option value="flex-end">flex-end</option> <option value="center" selected>center</option> <option value="space-between">space-between</option> <option value="space-around">space-around</option> <option value="space-evenly">space-evenly</option> <option value="start">start</option> <option value="end">end</option> <option value="left">left</option> <option value="right">right</option> <option value="baseline">baseline</option> <option value="first baseline">first baseline</option> <option value="last baseline">last baseline</option> <option value="safe center">safe center</option> <option value="unsafe center">unsafe center</option> <option value="safe right">safe right</option> <option value="unsafe right">unsafe right</option> <option value="safe end">safe end</option> <option value="unsafe end">unsafe end</option> <option value="safe flex-end">safe flex-end</option> <option value="unsafe flex-end">unsafe flex-end</option> </select> </div>
Result
Specifications
Specification | Status | Comment |
---|---|---|
CSS Box Alignment Module Level 3 The definition of ‘align-content’ in that specification. |
Working Draft | Adds the [ first | last ]? baseline, start, end, left, right, unsafe | safe values. |
CSS Flexible Box Layout Module The definition of ‘align-content’ in that specification. |
Candidate Recommendation | Initial definition |
developer.mozilla.org