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

Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 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.

egghead
egghead
~ 5 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today