Css grid item align

align-items

The CSS align-items property sets the align-self value on all direct children as a group. In Flexbox, it controls the alignment of items on the Cross Axis. In Grid Layout, it controls the alignment of items on the Block Axis within their grid area.

The interactive example below demonstrates some of the values for align-items using grid layout.

Try it

Syntax

/* Basic keywords */ align-items: normal; align-items: stretch; /* Positional alignment */ /* align-items does not take left and right values */ align-items: center; /* Pack items around the center */ align-items: start; /* Pack items from the start */ align-items: end; /* Pack items from the end */ align-items: flex-start; /* Pack flex items from the start */ align-items: flex-end; /* Pack flex items from the end */ align-items: self-start; /* Pack flex items from the start */ align-items: self-end; /* Pack flex items from the end */ /* Baseline alignment */ align-items: baseline; align-items: first baseline; align-items: last baseline; /* Overflow alignment (for positional alignment only) */ align-items: safe center; align-items: unsafe center; /* Global values */ align-items: inherit; align-items: initial; align-items: revert; align-items: revert-layer; align-items: unset; 

Values

The effect of this keyword is dependent of the layout mode we are in:

  • In absolutely-positioned layouts, the keyword behaves like start on replaced absolutely-positioned boxes, and as stretch on all other absolutely-positioned boxes.
  • In static position of absolutely-positioned layouts, the keyword behaves as stretch .
  • For flex items, the keyword behaves as stretch .
  • For grid items, this keyword leads to a behavior similar to the one of stretch , except for boxes with an aspect ratio or an intrinsic sizes where it behaves like start .
  • The property doesn’t apply to block-level boxes, and to table cells.
Читайте также:  Php change configuration file

The cross-start margin edges of the flex items are flushed with the cross-start edge of the line.

The cross-end margin edges of the flex items are flushed with the cross-end edge of the line.

The flex items’ margin boxes are centered within the line on the cross-axis. If the cross-size of an item is larger than the flex container, it will overflow equally in both directions.

The items are packed flush to each other toward the start edge of the alignment container in the appropriate axis.

The items are packed flush to each other toward the end edge of the alignment container in the appropriate axis.

The items are packed flush to the edge of the alignment container’s start side of the item, in the appropriate axis.

The items are packed flush to the edge of the alignment container’s end side of the item, in the appropriate axis.

baseline , first baseline , last baseline

All flex items are aligned such that their flex container baselines align. The item with the largest distance between its cross-start margin edge and its baseline is flushed with the cross-start edge of the line.

Flex items are stretched such that the cross-size of the item’s margin box is the same as the line while respecting width and height constraints.

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-items =
normal |
stretch |
|
[ ? ]

=
[ first | last ]? &&
baseline

=
unsafe |
safe

=
center |
start |
end |
self-start |
self-end |
flex-start |
flex-end

Examples

CSS

#container  height: 200px; width: 240px; align-items: 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-items: label> select id="values"> option value="normal">normaloption> option value="flex-start">flex-startoption> option value="flex-end">flex-endoption> option value="center" selected>centeroption> option value="baseline">baselineoption> option value="stretch">stretchoption> option value="start">startoption> option value="end">endoption> option value="self-start">self-startoption> option value="self-end">self-endoption> 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 self-end">safe self-endoption> option value="unsafe self-end">unsafe self-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.alignItems = evt.target.value; >); display.addEventListener("change", (evt) =>  container.className = evt.target.value; >); 

Result

Specifications

Источник

Полное визуальное руководство/шпаргалка по CSS Grid

Сегодня мы с вами рассмотрим свойства CSS Grid (далее также — Грид), позволяющие создавать адаптивные или отзывчивые макеты веб-страниц. Я постараюсь кратко, но полно объяснить, как работает каждое свойство.

Что такое CSS Grid ?

Грид — это макет для сайта (его схема, проект).

Грид-модель позволяет размещать контент сайта (располагать его определенным образом, позиционировать). Она позволяет создавать структуры, необходимые для обеспечения отзывчивости сайтов на различных устройствах. Это означает, что сайт будет одинаково хорошо смотреться на компьютере, телефоне и планшете.

Вот простой пример макета сайта, созданного с помощью Грида.

Архитектура CSS Grid

Как же Грид работает? Элементы Грида (grid items) располагаются вдоль главной или основной (main) и поперечной (cross) оси (axis). При помощи различных свойств мы можем манипулировать элементами для создания макетов.

Помимо прочего, у нас имеется возможность объединять строки и колонки подобно тому, как мы это делаем в Excel , что предоставляет нам большую гибкость, чем Флекс ( Flexbox ).

К слову, если вас интересует Флекс, вот соответствующая статья.

Схема CSS Grid

Схема содержит все возможные свойства, предоставляемые Гридом. Эти свойства делятся на:

Обратите внимание: красным цветом отмечены сокращения для свойств:


К концу настоящей статьи у вас будет полное понимание того, как работает каждое из них.

Настройка проекта

Для данного проекта требуются начальные знания HTML , CSS и умение работать с VSCode (или другим редактором по вашему вкусу). Делаем следующее:

  1. Создаем директорию для проекта, например, Project1 и открываем ее в редакторе ( cd Project1 , code . )
  2. Создаем файлы index.html и style.css
  3. Устанавливаем в VSCode сервер для разработки ( Live Server , расширение) и запускаем его

Или вы можете просто открыть Codepen (или любую другую песочницу) и начать писать код.

Все готово, можно приступать к делу.

HTML

Создаем 3 контейнера внутри body :

Источник

Box alignment in grid layout

The box alignment specification details how alignment works in various layout methods. On this page we explore how box alignment works in the context of CSS grid layout.

As this page aims to detail things which are specific to CSS Grid Layout and Box Alignment, it should be read in conjunction with the main box alignment page which details the common features of box alignment across layout methods.

Basic example

In this example using grid layout, there is extra space in the grid container after laying out the fixed width tracks on the inline (main) axis. This space is distributed using justify-content . On the block (cross) axis the alignment of the items inside their grid areas is controlled with align-items . The first item overrides the align-items value set on the group by setting align-self to center .

Grid axes

As a two-dimensional layout method, when working with grid layout we always have two axes on which to align our items. We have access to all of the box alignment properties to help us achieve this.

The inline axis is the axis that corresponds to the direction that words in a sentence would run in the writing mode used. Therefore, in a horizontal language such as English or Arabic the inline direction runs horizontally. Should you be in a vertical writing mode the inline axis will run vertically.

Inline axes are horizontal.

To align things on the inline axis you use the properties that start with justify- , justify-content , justify-items and justify-self .

The block axis crosses the inline axis in the direction that blocks are displayed down the page — for example paragraphs in English are displayed one below the other vertically. This, therefore is the block dimension.

To align things on the block axis you use the properties that start with align- , align-content , align-items and align-self .

The block axes are vertical.

Self alignment

These properties deal with aligning the item inside the grid area it is placed into. The properties align-items and justify-items are applied to the grid container and set the align-self and justify-self properties as a group. This means that you can set alignment for all of your grid Items at once, then override any items that need a different alignment by applying the align-self or justify-self property to the rules for the individual grid Items.

The initial value for align-self and justify-self is stretch so the item will stretch over the entire grid area. The exception to this rule is where the item has an intrinsic aspect ratio, for example an image. In this case the item will be aligned to start in both dimensions in order that the image is not distorted.

Content alignment

These properties deal with aligning the tracks of the grid when there is extra space to distribute. This scenario will occur if the tracks that you have defined total less than the total width of the grid container.

Gap and legacy grid-gap properties

The Grid specification originally contained the definition for the properties grid-row-gap , grid-column-gap and grid-gap . These have since been moved into the Box Alignment specification and renamed to row-gap , column-gap , and gap . This allows them to be used for other layout methods where a gap between items makes sense.

The updated properties have not yet been implemented in all browsers. Therefore, to use the gap properties in grid layout, you should use the grid-row-gap , grid-column-gap and grid-gap versions to ensure full compatibility. You could double up the properties and use both as you would for vendor prefixes.

Источник

Оцените статью