On this article, we’ll discover all the probabilities of the CSS Grid repeat() operate, which permits us to effectively create patterns of Grid columns and rows, and even to create responsive layouts with out media queries.

Desk of Contents
  1. Don’t repeat() Yourself
  2. Options for the repeat() Function
  3. Using Length Values with repeat()
  4. Using the min-content Keyword with repeat()
  5. Using the max-content Keyword with repeat()
  6. Using the auto Keyword with repeat()
  7. Using the minmax() Function with repeat()
  8. Using the fit-content() function with repeat()
  9. Using Named Lines with repeat()
  10. Using repeat() with auto-fit and auto-fill
  11. Using repeat() with auto-fit/auto-fill, minmax() and min()
  12. Understanding the Difference between auto-fit and auto-fill
  13. Useful Things to Know about repeat()
  14. Wrapping Up

Don’t repeat() Your self

The grid-template-columns and grid-template-rows properties permit us to explicitly set the variety of rows and columns we wish in a grid, and to specify how they need to be sized. This could develop into repetitive if we wish a number of rows and/or columns to be sized the identical method.

The repeat() operate can save us from having to repeat ourselves. For instance, we’d discover ourselves penning this:

grid-template-columns: 1fr 1fr 1fr 1fr 1fr;

As an alternative, we will write this:

grid-template-columns: repeat(5, 1fr);

Within the instance above, the repeat() operate lets us specify what number of columns we wish (5), and what dimension they need to all be (1fr — or one fraction of the obtainable area).

This makes our code extra environment friendly and simpler to learn. And that is only a easy instance. As we’ll see under, there’s much more we will do with the repeat() operate.

The next Pen exhibits a easy demo of the code above. An article containing ten divs is organized into 5 columns.

The demo above makes use of the CSS gap property. To be taught extra about grid format, take a look at our beginner’s guide to CSS Grid.

Choices for the repeat() Perform

We will really do quite a bit contained in the parentheses of repeat(). It takes two arguments, separated by a comma. The primary represents the “depend”, and the second represents the “tracks”: repeat(<depend>, <tracks>). (The phrase “observe” is a generic identify for a column or a row.)

The depend argument might be certainly one of three issues:

Clearly, a quantity worth units a particular variety of tracks. However auto-fit and auto-fill permit for various numbers of tracks relying on the obtainable area. This makes them very useful for responsive layouts without media queries. We’ll discover them intimately under.

The tracks argument specifies the tracks that shall be repeated. These are the choices for this argument:

As you possibly can see, there are many attainable choices for this argument, and so they can begin to look a bit complicated, particularly when a number of of them are mixed. We’ll attempt to maintain issues pretty easy right here in order that we don’t get misplaced within the weeds. In most circumstances, the tracks argument is pretty easy and intuitive.

Setting Teams of Columns with repeat()

Earlier than we discover the assorted arguments that can be utilized with repeat(), it’s value noting that repeat() can be utilized to create patterns of columns.

For instance, take into account this “longhand” code for a six-column grid:

article {
  grid-template-columns: 1fr 2fr 1fr 2fr 1fr 2fr;

We will rewrite this like so, utilizing repeat():

article {
  grid-template-columns: repeat(3, 1fr 2fr);

This tells the browser to repeat a sample thrice — of a column 1fr broad, adopted by a column 2fr broad. The demo under exhibits this in motion.

Utilizing Size Values with repeat()

We’ve already seen a size worth of 1fr used with repeat(). The benefit of the fr unit is that it sizes tracks in keeping with the obtainable area with out us having to fret about how a lot area is accessible. However we will additionally use different size models the place we’d like them.

For instance, let’s set three column tracks and provides them a width of 120 pixels:

article {
  grid-template-columns: repeat(3, 120px);

The next CodePen demo exhibits the end result.

The columns now have a hard and fast width, which gained’t change even when the container is simply too slim. Strive taking part in round with the browser width within the Pen above. Additionally attempt swapping pixels for different size models, akin to 5em, 10ch, 15%, and so forth, to see their impact.

Utilizing the min-content Key phrase with repeat()

The min-content key phrase units a observe to be solely as broad or tall as its minimal content material. Within the demo under, we’ve got three columns, every of which is ready to min-content, so every column is as broad because the longest phrase it incorporates:

article {
  grid-template-columns: repeat(3, min-content);

Utilizing the max-content Key phrase with repeat()

The max-content key phrase mainly does the other of min-content: it bases the observe dimension on the biggest quantity of content material in a grid cell. Within the demo under, the column widths are primarily based on the cell with the biggest quantity of content material:

article {
  grid-template-columns: repeat(3, max-content);

Utilizing the auto Key phrase with repeat()

When used with repeat(), the auto key phrase maxes out at max-content and minutes out at min-content.

Take into account the next sample of columns:

article {
  grid-template-columns: repeat(3, auto 1fr);

Right here, we’ll have six columns, every odd-numbered one set to a width of auto. Within the CodePen demo under, we will see that, the place there’s sufficient area, the divs with “auto” textual content max out at max-content, and the 1fr divs share the remaining area. Because the browser narrows, the auto columns proceed to get narrower till they attain the min-content threshold.

Within the demo above, the divs solely begin to overflow the container as soon as every column has reached its min-content threshold. (That’s, the textual content can’t wrap any additional.)

Notice: auto solely appears to behave as described above when combined with different values. By itself — akin to repeat(3, auto) — it behaves identical to we’re setting repeat(3, 1fr).

Utilizing the minmax() Perform with repeat()

The minmax() operate takes two arguments of its personal — a minimal and most worth, separated by a comma. So with minmax(), we will set a variety of attainable sizes for tracks in a versatile atmosphere.

For instance, we may set a column to minmax(40px, 100px), which suggests its minimal attainable width is 40px and its most attainable width is 100px.

Each arguments of minmax() can take size values like fr, px, em, % and ch, in addition to min-content, max-content and auto. Nonetheless, it’s finest to make use of a size worth for at the least one argument, because the key phrases aren’t speculated to work as each arguments (though I discover this generally does work — akin to minmax(min-content, max-content)).

The next code units 5 columns, every with a minimal width of 60px and a most width of 1fr:

article {
  grid-template-columns: repeat(5, minmax(60px, 1fr));

This works effectively till the minimal width of 60px is reached. After that time, the content material begins to hang around of its container. We’ll see the way to get a greater end result quickly.

Utilizing the minmax() operate with min() or max()

The minmax() operate can even have both the min() or max() operate as an argument. These each take two values. The min() operate applies whichever is the smaller of its two values, and the max() operate applies whichever is the bigger worth. That is helpful in responsive environments.

For instance:

article {
  grid-template-columns: repeat(5, minmax(min(60px, 8vw), 1fr));

The code above units 5 columns. On broad browsers, the 5 columns will all be equally spaced at 1fr. On narrower gadgets, the columns will get narrower and narrower. They’ll cease shrinking as soon as they hit whichever is the decrease of 60px and 8vw. So we nonetheless can discover ourselves with content material hanging out of the container on slim screens; there’s nonetheless additional to go to be absolutely responsive.

In the event you’re discovering the mix of minmax(), min() and max() a bit underwhelming at this stage, dangle in there, as their actual energy shall be seen under after we meet auto-fit and auto-fill.

Utilizing the fit-content() operate with repeat()

The fit-content() operate takes a single argument, which represents the utmost dimension a observe can develop to. So the observe might be versatile as much as that time. fit-content() can take any size worth, akin to fr, px, em, % and ch.

For instance, if we set three columns and fit-content(120px), the column widths shall be responsive up till a width of 120px:

article {
  grid-template-columns: repeat(3, fit-content(120px));

Utilizing Named Traces with repeat()

In Grid format, the vertical and horizontal traces round tracks are numbered by default. When setting grid-template-columns and grid-template-rows, we can provide names to these traces. This makes it simpler to focus on these traces when putting content material on the grid (as we don’t should go in and depend the grid traces).

Right here’s a easy instance. The named traces are the bits in sq. brackets ([]):

article {
  grid-template-columns: [sidebar] 300px [content-start] 1fr [content-end];

The code above offers us two columns. The left-most vertical grid line (no 1) is named “sidebar”, the center grid line (quantity 2) is named “content-start”, and the ultimate grid line (quantity 3) is named “content-end”.

We will additionally used named traces inside our repeat() operate:

article {
  grid-template-columns: repeat(5, [yin] 1fr [yang]);

Which means every of our columns now has a line to the left known as yin and a line to the suitable known as yang.

The developer tools showing our grid lines around each track and the named column lines

It may appear to make life tougher if every line has the identical identify, however we will nonetheless goal them individually. For instance:

  • we will goal the primary yin line with grid-column: yin
  • we will goal the second yin line with grid-column: yin 2
  • we will set a column to span three rows from the second yin line: grid-column: yin 2 / span 3
  • we will set a column to span from the second yin to the top with grid-column: yin 2 / yang -1

Naming traces inside repeat() might be most helpful the place repeat() is combined with different values, like so:

article {
  grid-template-columns: [main-start] auto repeat(5, [yin] 1fr [yang]) [sidebar] 300px [main-end];

Named lines set inside and outside of the repeat function

I gained’t delve additional into named traces and the way to use them right here, because it’s a separate subject, however you possibly can learn extra about named grid lines on MDN.

Utilizing repeat() with auto-fit and auto-fill

The auto-fit and auto-fill key phrases are options to setting a hard and fast variety of tracks. They inform the browser to suit as many tracks right into a given area as attainable. For instance:

article {
  grid-template-columns: repeat(auto-fit, 150px);

Within the demo above, divs are set to a width of 150px, and people that may’t match on one line drop to the subsequent. If we alter auto-fit to auto-fill, we gained’t see a distinction, as a result of beneath these situations, they each do the identical factor. The variations between them solely develop into apparent beneath particular circumstances.

At this level, auto-fit to auto-fill are okay, however nothing particularly flash. It’s once they’re mixed with minmax() and min() that the actual magic begins to occur, so let’s take a look at that subsequent.

Utilizing repeat() with auto-fit/auto-fill, minmax() and min()

In the event you aren’t in love with repeat() but, the mix of repeat() with auto-fit, minmax() and min() will certainly see Cupid’s arrow pierce your cussed coronary heart. Their mixture lets us create really responsive layouts with out the usage of media queries.

Utilizing auto-fit and minmax() with repeat()

Take into account the next CSS:

article {
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));

On this instance, minmax() units a minimal column width of 200px and a most of 1fr. The demo under exhibits this in motion.

Every div have to be at the least 200px broad. If there’s further area to the suitable (much less that 200 pixels), the divs increase to fill the area. If we widen the browser, one other div is added to the row as soon as one other 200 pixels of area is accessible. The identical occurs in reverse: as we slim the browser, the final div within the row will drop as soon as there isn’t at the least 200px of area for it to suit into. And as soon as it has dropped, the remaining divs increase to replenish the row.

Once more, if we swap auto-fit for auto-fill, we’ll see the identical conduct.

There’s one limitation with this instance, although. If we make the browser window slim sufficient, we’ll find yourself with a single column. As that column will get narrower than 200px, the divs will begin to overflow their container.

Once minmax reaches its lower limit, the blue divs overflow their container, sticking out to the right

We will forestall this overflow from taking place by bringing min() into the combo, so let’s take a look at that subsequent.

Utilizing auto-fit, minmax() and min() with repeat()

We will management what occurs at small widths by introducing min(). Let’s replace our code to appear like this:

article {
  grid-template-columns: repeat(auto-fit, minmax(min(200px, 100%), 1fr));

Now there are two choices for the minimal column width. The browser will select whichever is smallest. As soon as the column is narrower than 200px, 100% is the smaller worth, so it prevails. And which means the only remaining column is now set to width: 100%, so it should proceed to suit properly into its container at ever lowering widths. (Squeeze the browser window down so far as you possibly can to see this in follow.)

For a extra real-world demo of utilizing repeat() with auto-fit, minmax() and min(), take a look at the next CodePen demo of a responsive picture gallery. This demo additionally makes use of the aspect-ratio property, which we lined in How to Use CSS aspect-ratio.

Understanding the Distinction between auto-fit and auto-fill

Within the examples we’ve seen up to now, there seems to be no distinction by any means between auto-fit and auto-fill. The distinction solely seems in sure conditions, which we’ll briefly cowl now.

We’ll strip our demo HTML down in order that there are solely 4 divs, and set the next CSS:

article {
  grid-template-columns: repeat(auto-fill, minmax(min(100px, 100%), 1fr));

The picture under exhibits what we get with auto-fill.

The browser leaves space for more divs

The browser is calculating what number of divs may match within the container and is leaving area for them. Every of the prevailing divs is 110px broad, as are the areas left to the suitable.

Let’s swap to auto-fit:

article {
  grid-template-columns: repeat(auto-fit, minmax(min(100px, 100%), 1fr));

The picture under exhibits what we get with auto-fit.

The browser fills up the remaining space with the existing divs

With auto-fit, the browser additionally calculates area for extra divs, however then collapses that area right down to zero width and lets the prevailing divs increase to take up all of the area. Within the picture above, you possibly can see that the top column line remains to be numbered 8. The 8 is stacked above grid traces 7, 6 and 5.

So what are we to make of all this? Realistically, in most if not all circumstances we’re going to wish to use auto-fit, as a result of we gained’t usually need area to stay empty after we might be utilizing it for our content material.

You possibly can mess around with auto-fit and auto-fill in this CodePen demo. Strive altering auto-fit to auto-fill, and widen and contract the browser to see how they each behave.

Helpful Issues to Find out about repeat()

As famous above, the repeat() operate can be utilized as a part of an extended declaration with grid-template-columns and grid-template-rows. A lot of the buddies we’ve met right here — size models, min-content, max-content, auto, minmax(), fit-content(), and named traces — work alongside repeat() in addition to inside it. (You possibly can see examples of them working with grid-template-columns and grid-template-rows on MDN.)

Some combos usually are not allowed for the observe argument. For instance, we will’t use one thing like repeat(auto-fill, 1fr). auto-fit and versatile models can’t play collectively, as a result of we’d like a hard and fast measure in there someplace, akin to minmax(100px, 1fr).

As we’ve seen, the minmax() operate can have both a nested min() or max() operate. It will possibly additionally include certainly one of auto, min-content, max-content, however not two. For instance, we may use minmax(50px, max-content), however not minmax(min-content, max-content) (though, to be trustworthy, I’ve discovered that a few of these combos do appear to work anyway).

The repeat() notation can’t be nested. So we will’t have a repeat() inside a repeat(). However we actually can have repeat() features facet by facet — akin to repeat(5, 1fr) 100px repeat(2, 50px).

Wrapping Up

The repeat() operate is an extremely useful gizmo for effectively laying out repeating patterns of grid columns and rows. It may be used to create absolutely responsive layouts with out media queries in only a single line of code.

Normally, you gained’t have to get too far down within the weeds with repeat(). Its most spectacular function is summed up in a primary instance like this:

repeat(auto-fit, minmax(min(50px, 100%), 1fr))

Ensure that to maintain that line of code in your again pocket, as it should are available in very useful.

You possibly can be taught extra in regards to the repeat() operate right here:

For a extra common introduction to CSS Grid format, see An Introduction to CSS Grid Layouts.