Css display grid выравнивание

How to Center the Content in Grid

In this tutorial, we’ll demonstrate how to center the content in Grid. Below, you can see all the possible solutions to this problem. Let’s discuss them.

Solution with Flexbox

One of the easiest ways of centering the content of grid items is using Flexbox. Set the display to «grid» for the grid container, and «flex» for grid items. Then, add the align-items and justify-content properties, both with the «center» value, to grid items.

Example of centering the content in Grid with Flexbox:

html> html> head> title>Title of the document title> style> .grid-container < display: grid; grid-template-columns: 1fr 1fr; grid-auto-rows: 60px; grid-gap: 20px; > .grid-item < display: flex; align-items: center; justify-content: center; > .grid-container < background-color: #fff; border: 1px solid #666; padding: 20px; > .grid-item < background-color: #dce0dd; border: 1px solid #666; > style> head> body> div class="grid-container"> div class="grid-item">A centered text div> div class="grid-item">A centered text div> div class="grid-item"> img src="http://i.imgur.com/60PVLis.png" width="40" height="40" alt="image"> div> div class="grid-item"> img src="http://i.imgur.com/60PVLis.png" width="40" height="40" alt="image"> div> div> body> html>

Result

Solution with Grid Layout

This solution is similar to the previous, but here the centering is done with grid properties.

Читайте также:  After in inline css

In the example below, we set the display of grid items to «grid», instead of «flex». Also, we use the justify-items property instead of justify-content.

Example of centering the content in Grid with Grid Layout:

html> html> head> title>Title of the document title> style> grid-container < display: grid; grid-template-columns: 1fr 1fr; grid-auto-rows: 60px; grid-gap: 20px; > grid-item < display: grid; align-items: center; justify-items: center; > grid-container < background-color: #fff; border: 1px solid #666; padding: 20px; > grid-item < background-color: #dce0dd; border: 1px solid #666; > style> head> body> grid-container> grid-item>A centered text grid-item> grid-item>A centered text grid-item> grid-item>img src="http://i.imgur.com/60PVLis.png" width="40" height="40" alt="text"> grid-item> grid-item>img src="http://i.imgur.com/60PVLis.png" width="40" height="40" alt="text"> grid-item> grid-container> body> html>

Solution with auto margins

You can also use the CSS margin property with its «auto» value to center grid items vertically and horizontally. Apply this property to the and elements. Set the display of grid items to «flex».

Example of centering the content in Grid with auto margins:

html> html> head> title>Title of the document title> style> grid-container < display: grid; grid-template-columns: 1fr 1fr; grid-auto-rows: 60px; grid-gap: 20px; > grid-item < display: flex; > span, img < margin: auto; > grid-container < background-color: #fff; border: 1px solid #666; padding: 20px; > grid-item < background-color: #dce0dd; border: 1px solid #666; > style> head> body> grid-container> grid-item>span>A centered text span> grid-item> grid-item>span>A centered text span> grid-item> grid-item>img src="http://i.imgur.com/60PVLis.png" width="40" height="40" alt="text"> grid-item> grid-item>img src="http://i.imgur.com/60PVLis.png" width="40" height="40" alt="text"> grid-item> grid-container> body> html>

Solution with the CSS text-align property

Use the text-align property with the «center» value to center the content of grid items horizontally. Apply it to the grid container.

Читайте также:  Call style in html

Example of horizontally centering the content in Grid with the text-align property:

html> html> head> title>Title of the document title> style> grid-container < display: grid; grid-template-columns: 1fr 1fr; grid-auto-rows: 60px; grid-gap: 20px; text-align: center; > grid-container < background-color: #fff; border: 1px solid #666; padding: 20px; > grid-item < background-color: #dce0dd; border: 1px solid #666; > style> head> body> grid-container> grid-item>A centered text grid-item> grid-item>A centered text grid-item> grid-item>img src="http://i.imgur.com/60PVLis.png" width="40" height="40" alt="text"> grid-item> grid-item>img src="http://i.imgur.com/60PVLis.png" width="40" height="40" alt="text"> grid-item> grid-container> body> html>

For vertical centering, the vertical-align property with the «middle» value will not work, as it is only used for inline and table-cell containers.

Solution with the CSS position property

This solution allows you to center elements that must be removed from the document flow. Set the position property to «absolute» on the element that must be centered, and use the «relative» value on the ancestor that serves as a containing block.

Example of centering the content in Grid with the position property:

html> html> head> title>Title of the document title> style> grid-container < display: grid; grid-template-columns: 1fr 1fr; grid-auto-rows: 60px; grid-gap: 20px; > grid-item < position: relative; text-align: center; > span, img < position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); > grid-container < background-color: #fff; border: 1px solid #666; padding: 20px; > grid-item < background-color: #dce0dd; border: 1px solid #666; > style> head> body> grid-container> grid-item>span>A centered text span> grid-item> grid-item>span>A centered text span> grid-item> grid-item>img src="http://i.imgur.com/60PVLis.png" width="40" height="40" alt="text"> grid-item> grid-item>img src="http://i.imgur.com/60PVLis.png" width="40" height="40" alt="text"> grid-item> grid-container> body> html>

Источник

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

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

Читайте также:  Выравнивание текста с помощью CSS

Что такое 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 :

Источник

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