Home > Blockchain >  Grid CSS repeat function creating more than specified columns
Grid CSS repeat function creating more than specified columns

Time:03-07

So im practicing CSS grid and im learning about the "repeat()" function. the code in question is: grid-template-columns: repeat(2, 20px 50px)

in the explanation it says "This code will create four columns where the first and third columns will be 20 pixels wide and the second and fourth will be 50 pixels wide." But i thought it would only create 2 columns because we have only specified "2" in the function?

CodePudding user response:

Some CSS grid tutorials introduce repeat() as a quick way to write more concise CSS rules. So for instance, rather than typing:
grid-template-columns: 1fr 1fr 1fr 1fr 1fr;

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

So what's going on... in the repeat() function, the first value defines the number of repetitions; the second value defines what will be repeated.

Let's work backwards from your example:
grid-template-columns: repeat(2, 20px 50px);

You've got a 20px 50px structure (two columns), and you've set that to repeat 2 times. That's a two-column structure twice, hence 4. Repeating it 3 times would be 6 columns, 4 would make 8 and so on.

For what it's worth. These declarations are the same: grid-template-columns: repeat(2, 20px 50px); grid-template-columns: 20px 50px 20px 50px;

CodePudding user response:

The repeat(numberOfRepetitions, columnOrRowDefinitions) function takes two arguments:

  1. numberOfRepetitions tells the browser how often you want the second argument repeated.

  2. columnOrRowDefinitions telss the browser which column or row definitions are to be repeated.

Let's look at the arguments you provided:

numberOfRepetitions: 2 // you asked for repeating twice.
columnOrRowDefinitions: 20px 50px // That is already two rows/columns.

  • Related