- align-content
- Try it
- Syntax
- Values
- Formal definition
- Formal syntax
- Examples
- CSS
- HTML
- Result
- Specifications
- Выравниваем блок по центру страницы
- Вариант 1. Отрицательный отступ.
- Вариант 2. Автоматический отступ.
- Вариант 3. Таблица.
- Вариант 4. Псевдо-элемент.
- Вариант 5. Flexbox.
- Вариант 6. Transform.
- Вариант 7. Кнопка.
- Бонус
align-content
The CSS align-content property sets the distribution of space between and around content items along a flexbox’s cross-axis or a grid’s block axis.
The interactive example below uses Grid Layout to demonstrate some of the values of this property.
Try it
This property has no effect on single line flex containers (i.e. ones with flex-wrap: nowrap ).
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: revert; align-content: revert-layer; align-content: unset;
Values
The items are packed flush to each other against the start edge of the alignment container in the cross axis.
The items are packed flush to each other against the end edge of the alignment container in the cross axis.
The items are packed flush to each other against 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 like start .
The items are packed flush to each other against 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 like end .
The items are packed flush to each other in the center of the alignment container along the cross axis.
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 for first baseline is start , the one for last baseline is end .
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 start edge of the alignment container in the cross axis, and the last item is flush with the end edge of the alignment container in the cross axis.
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.
The items are evenly distributed within the alignment container along the cross axis. The spacing between each pair of adjacent items, the start edge and the first item, and the end edge and the last item, are all exactly the same.
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 by max-height / max-width (or equivalent functionality), so that the combined size exactly fills the alignment container along the cross axis.
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 .
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 definition
Formal syntax
align-content =
normal |
|
|
?
=
[ first | last ]? &&
baseline
=
space-between |
space-around |
space-evenly |
stretch
=
unsafe |
safe
=
center |
start |
end |
flex-start |
flex-end
Examples
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">1div> div id="item2">2div> div id="item3">3div> div id="item4">4div> div id="item5">5div> div id="item6">6div> div> div class="row"> label for="display">display: label> select id="display"> option value="flex">flexoption> option value="grid">gridoption> select> div> div class="row"> label for="values">align-content: label> select id="values"> option value="normal">normaloption> option value="stretch">stretchoption> option value="flex-start">flex-startoption> option value="flex-end">flex-endoption> option value="center" selected>centeroption> option value="space-between">space-betweenoption> option value="space-around">space-aroundoption> option value="space-evenly">space-evenlyoption> option value="start">startoption> option value="end">endoption> option value="baseline">baselineoption> option value="first baseline">first baselineoption> option value="last baseline">last baselineoption> option value="safe center">safe centeroption> option value="unsafe center">unsafe centeroption> option value="safe right">safe rightoption> option value="unsafe right">unsafe rightoption> option value="safe end">safe endoption> option value="unsafe end">unsafe endoption> option value="safe flex-end">safe flex-endoption> option value="unsafe flex-end">unsafe flex-endoption> select> div>
const values = document.getElementById("values"); const display = document.getElementById("display"); const container = document.getElementById("container"); values.addEventListener("change", (evt) => container.style.alignContent = evt.target.value; >); display.addEventListener("change", (evt) => container.className = evt.target.value; >);
Result
Specifications
Выравниваем блок по центру страницы
Очень часто стоит задача выровнять блок по центру страницы / экрана, да ещё и так, чтобы без ява-скрипта, без задания жёстких размеров или отрицательных отступов, ещё чтобы и скроллбары работали у родителя, если блок превышает его размеры. В сети ходят достаточно много однообразных примеров как выровнять блок по центру экрана. Как правило большинство из них основаны на одних принципах.
Ниже представлены основные способы решения задачи, их плюсы и минусы. Чтобы понимать суть примеров, рекомендую уменьшить высоту / ширину окошка Result в примерах по указанным ссылкам.
Вариант 1. Отрицательный отступ.
Позиционируем блок атрибутами top и left на 50%, и заранее зная высоту и ширину блока, задаём отрицательный margin, который равен половине размера блока. Огромным минусом данного варианта является то, что нужно подсчитывать отрицательные отступы. Так же блок не совсем корректно ведёт себя в окружении скроллбаров — он попросту обрезается так как имеет отрицательные отступы.
Вариант 2. Автоматический отступ.
Менее распространённый, но схожий с первым. Для блока задаём ширину и высоту, позиционируем атрибутами top right bottom left на 0, и задаём margin auto. Плюсом данного варианта являются рабочие скроллбары у родителя, если у последнего задана 100% ширина и высота. Минусом данного способ является жёсткое задание размеров.
Вариант 3. Таблица.
Задаём родителю табличные стили, ячейке родителя устанавливаем выравнивание текста по центру. А блоку задаём модель строчного блока. Минусами мы получаем не рабочие скроллбары, и в целом не эстетичность «эмуляции» таблицы.
Чтобы добавить скролл в данный пример, придётся добавить в конструкцию ещё один элемент.
Пример: jsfiddle.net/serdidg/xkb615mu.
Вариант 4. Псевдо-элемент.
Данный вариант лишён всех проблем, перечисленных у предыдущих способов, а так же решает первоначально поставленные задачи. Суть состоит в том, чтобы у родителя задать стили псевдо-элементу before, а именно 100% высоту, выравнивание по центру и модель строчного блока. Так же само и у блока ставится модель строчного блока, выравнивание по центру. Чтобы блок не «падал» под псевдо-элемент, когда размеры первого больше чем родителя, указываем родителю white-space: nowrap и font-size: 0, после чего у блока отменяем эти стили следующими — white-space: normal. В данном примере font-size: 0 нужен для того, чтобы убрать образовавшийся пробел между родителем и блоком в связи с форматированием кода. Пробел можно убрать и иными способами, но лучшим считается просто его не допускать.
либо, если вам нужно, чтобы родитель занимал только высоту и ширину окна, а не всей страницы:
Вариант 5. Flexbox.
Одним из самых простых и элегантных способов является использования flexbox. Но имейте ввиду, что центральное позиционирование сохраняется даже если родительский блок меньше дочернего, последний будет выходить за рамки и обрезаться.
В случае, если при уменьшении родительского блока дочерний не должен обрезаться по краям, используйте авто маржины:
Вариант 6. Transform.
Подходит в случае если мы ограничены структурой, и нет возможности манипулировать родительским элементом, а блок выровнять как-то нужно. На помощь придёт css функция translate() . При значение 50% абсолютное позиционирование расположит верхний левый угол блока точно по центру, затем отрицательное значение translate сдвинет блок относительно своих собственных размеров. Учтите, что могут всплыть негативные эффекты в виде размытых граней или начертания шрифта. Также подобный способ может привести к проблемах с вычислением положения блока с помощью java-script’а. Иногда для компенсации потери 50% ширины из-за использования css свойства left может помочь заданное у блока правило: margin-right: -50%; .
Вариант 7. Кнопка.
Пользователь azproduction предложил вариант, где блок обрамляется в тег button. Кнопка имеет свойство центрировать всё, что находится у неё внутри, а именно элементы строчной и блочно-строчной (inline-block) модели. На практике использовать не рекомендую.
Бонус
Используя идею 4-го варианта, можно задавать внешние отступы для блока, и при этом последний будет адекватно отображаться в окружении скроллбаров.
Пример: jsfiddle.net/serdidg/ugnp8ry7.
Так же можно выравнивать картинку по центру, и в случае если картинка больше родителя, масштабировать её по размеру родителя.
Пример: jsfiddle.net/serdidg/Lhpa1s70.
Пример с большой картинкой: jsfiddle.net/serdidg/tor2yudn.