Use the repeat() CSS Function to Efficiently Define CSS Grid Rows and Columns

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

Typing the same thing over and over again is tiring!

The repeat() CSS function allows you to define a large number of columns or rows that exhibit a recurring pattern to be written in a more compact form. This function can be used in the CSS Grid properties grid-template-columns and grid-template-rows.

Instructor: [0:01] Writing 1fr three times isn't that bad, but what if you had five columns? It gets a little tedious. There's a nifty trick in CSS Grids to help you save a few seconds.

[0:10] We have here 10 portfolio items and five columns at 1fr each. Let's rewrite this using repeat(). You specify how many columns you want as a number and then the width. I want (5, 1fr). If it went smoothly, even if you refresh, nothing should change on the browser side, because you are just rewriting the same thing as you had before.

[0:32] You can get a little creative with this, too. Say you want every other item to be 2fr in width instead of 1fr. You can still use the repeat function to do that. We'll have four columns this time to make it easier. Here we go. Every other column is 2fr, and it just repeats until there's no more items left.