- repeat()
- Try it
- Syntax
- Values
- Examples
- Specifying grid columns using repeat()
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Полное визуальное руководство/шпаргалка по CSS Grid
- Что такое CSS Grid ?
- Архитектура CSS Grid
- Схема CSS Grid
- Настройка проекта
- HTML
repeat()
Baseline is determined by this web feature being supported on the current and the previous major versions of major browsers.
The repeat() CSS function represents a repeated fragment of the track list, allowing a large number of columns or rows that exhibit a recurring pattern to be written in a more compact form.
Try it
This function can be used in the CSS Grid properties grid-template-columns and grid-template-rows .
Syntax
/* values */ repeat(4, 1fr) repeat(4, [col-start] 250px [col-end]) repeat(4, [col-start] 60% [col-end]) repeat(4, [col-start] 1fr [col-end]) repeat(4, [col-start] min-content [col-end]) repeat(4, [col-start] max-content [col-end]) repeat(4, [col-start] auto [col-end]) repeat(4, [col-start] minmax(100px, 1fr) [col-end]) repeat(4, [col-start] fit-content(200px) [col-end]) repeat(4, 10px [col-start] 30% [col-middle] auto [col-end]) repeat(4, [col-start] min-content [col-middle] max-content [col-end]) /* values */ repeat(auto-fill, 250px) repeat(auto-fit, 250px) repeat(auto-fill, [col-start] 250px [col-end]) repeat(auto-fit, [col-start] 250px [col-end]) repeat(auto-fill, [col-start] minmax(100px, 1fr) [col-end]) repeat(auto-fill, 10px [col-start] 30% [col-middle] 400px [col-end]) /* values */ repeat(4, 250px) repeat(4, [col-start] 250px [col-end]) repeat(4, [col-start] 60% [col-end]) repeat(4, [col-start] minmax(100px, 1fr) [col-end]) repeat(4, [col-start] fit-content(200px) [col-end]) repeat(4, 10px [col-start] 30% [col-middle] 400px [col-end])
The repeat() function takes two arguments:
- repeat count: the first argument specifies the number of times that the track list should be repeated. It is specified with an integer value of 1 or more, or with the keyword values auto-fill or auto-fit . These keyword values repeat the set of tracks as many times as is needed to fill the grid container.
- tracks: the second argument specifies the set of tracks that will be repeated. Fundamentally this consists of one or more values, where each value represents the size of that track. Each size is specified using either a value or a value. You can also specify one or more line names before or after each track, by providing values before and/or after the track size.
If you use auto-fill or auto-fit to set the repeat count, you may only specify track sizes using the type, not the type. This give us three main syntax forms for repeat() :
- , which uses:
- an integer to set the repeat count
- values to set track sizes.
- auto-fill or auto-fit to set the repeat count
- to set track sizes.
- an integer to set the repeat count
- values to set track sizes.
Then if a property declaration uses , it is only allowed to use for any additional repeat() calls. For example, this is invalid, because it combines the form with the form:
.wrapper grid-template-columns: repeat(auto-fill, 10px) repeat(2, minmax(min-content, max-content)); >
There is a fourth form, , which is used to add line names to subgrids. It only used with the subgrid keyword and only specifies line names, not track sizes.
Values
One of the following forms:
- a value
- a minmax() function with:
- min given as a value
- max given as one of a value, a value, or one of the following keywords: min-content , max-content , or auto
- min given as a value or one of the following keywords: min-content , max-content , or auto
- max given as a value.
A non-negative dimension with the unit fr specifying the track’s flex factor. Each -sized track takes a share of the remaining space in proportion to its flex factor.
A positive integer length.
A non-negative percentage relative to the inline size of the grid container in column grid tracks, and the block size of the grid container in row grid tracks. If the size of the grid container depends on the size of its tracks, then the must be treated as auto . The user-agent may adjust the intrinsic size contributions of the track to the size of the grid container and increase the final size of the track by the minimum amount that would result in honoring the percentage.
One of the following forms:
- a value, a value, or one of the following keywords: min-content , max-content , or auto
- a minmax() function with:
- min given as a value, or one of the following keywords: min-content , max-content , or auto
- max given as a value, a value, or one of the following keywords: min-content , max-content , or auto
As a maximum, identical to max-content . As a minimum it represents the largest minimum size (as specified by min-width / min-height ) of the grid items occupying the grid track.
If the grid container has a definite or maximal size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container. Treating each track as its maximal track sizing function (each independent value used to define grid-template-rows or grid-template-columns ), if that is definite. Otherwise, as its minimum track sizing function, and taking grid-gap into account. If any number of repetitions would overflow, then the repetition is 1 . Otherwise, if the grid container has a definite minimal size in the relevant axis, the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement. Otherwise, the specified track list repeats only once.
Behaves the same as auto-fill , except that after placing the grid items any empty repeated tracks are collapsed. An empty track is one with no in-flow grid items placed into or spanning across it. (This can result in all tracks being collapsed, if they’re all empty.)
A collapsed track is treated as having a single fixed track sizing function of 0px , and the gutters on either side of it collapse.
For the purpose of finding the number of auto-repeated tracks, the user agent floors the track size to a user agent specified value (e.g., 1px ), to avoid division by zero.
Represents the largest max-content contribution of the grid items occupying the grid track.
Represents the largest min-content contribution of the grid items occupying the grid track.
Examples
Specifying grid columns using repeat()
HTML
div id="container"> div>This item is 50 pixels wide.div> div>Item with flexible width.div> div>This item is 50 pixels wide.div> div>Item with flexible width.div> div>Inflexible item of 100 pixels width.div> div>
CSS
#container display: grid; grid-template-columns: repeat(2, 50px 1fr) 100px; grid-gap: 5px; box-sizing: border-box; height: 200px; width: 100%; background-color: #8cffa0; padding: 10px; > #container > div background-color: #8ca0ff; padding: 5px; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 18, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.Полное визуальное руководство/шпаргалка по CSS Grid
Сегодня мы с вами рассмотрим свойства CSS Grid (далее также — Грид), позволяющие создавать адаптивные или отзывчивые макеты веб-страниц. Я постараюсь кратко, но полно объяснить, как работает каждое свойство.
Что такое CSS Grid ?
Грид — это макет для сайта (его схема, проект).
Грид-модель позволяет размещать контент сайта (располагать его определенным образом, позиционировать). Она позволяет создавать структуры, необходимые для обеспечения отзывчивости сайтов на различных устройствах. Это означает, что сайт будет одинаково хорошо смотреться на компьютере, телефоне и планшете.
Вот простой пример макета сайта, созданного с помощью Грида.
Архитектура CSS Grid
Как же Грид работает? Элементы Грида (grid items) располагаются вдоль главной или основной (main) и поперечной (cross) оси (axis). При помощи различных свойств мы можем манипулировать элементами для создания макетов.
Помимо прочего, у нас имеется возможность объединять строки и колонки подобно тому, как мы это делаем в Excel , что предоставляет нам большую гибкость, чем Флекс ( Flexbox ).
К слову, если вас интересует Флекс, вот соответствующая статья.
Схема CSS Grid
Схема содержит все возможные свойства, предоставляемые Гридом. Эти свойства делятся на:
Обратите внимание: красным цветом отмечены сокращения для свойств:
К концу настоящей статьи у вас будет полное понимание того, как работает каждое из них.
Настройка проекта
Для данного проекта требуются начальные знания HTML , CSS и умение работать с VSCode (или другим редактором по вашему вкусу). Делаем следующее:
- Создаем директорию для проекта, например, Project1 и открываем ее в редакторе ( cd Project1 , code . )
- Создаем файлы index.html и style.css
- Устанавливаем в VSCode сервер для разработки ( Live Server , расширение) и запускаем его
Или вы можете просто открыть Codepen (или любую другую песочницу) и начать писать код.
Все готово, можно приступать к делу.
HTML
Создаем 3 контейнера внутри body :