Hey there!

Today, I created this pen:

It's one HTML element that turns every child into a square.

In this post, I'd like to cover the calculation of the rows.

  --row-size: calc(
    ( var(--content-width) - (var(--gutter) * (var(--columns) - 1))
    ) / var(--columns)

To understand why it's constructed like this we first need to take a look at all the pieces.

the tools

--row-size is the variable that's later on used in grid-auto-rows: ..

calc() is used to perform calculating in css I'd recommend to check it out if you haven't seen it before

--content-width is a variable that is used to limit the total width of the container. I tend to have one variable that limits the width which is then used in the header, footer & content so you have a consistent look.

--gutter is the size between the tiles

--column is the amount of columns


The repeat() syntax works like this: repeat(AMOUNT OF TIMES, SIZE) fr stands for fraction

Let's assume our --columns variable has the value 3.

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

resolves in 3 columns with the size of 1 fraction of the container


With grid-row-gap and grid-column-gap we add space between the rows and columns.

The variable --gutter is used here.

the calculation

  --row-size: calc(
    ( var(--content-width) - (var(--gutter) * (var(--columns) - 1))
    ) / var(--columns)

Now we recognize the variables and know what they're doing.

What makes the items square is basically: content-width / columns

This does not work because we have a variable gutter size, so we have to subtract it from the content width.

step by step:

  1. var(--columns) - 1) This is the amount of gutters. If we have 2 columns, we have 1 gutter. If we have 6 columns, we have 5 gutters.

  2. var(--gutter) * (var(--columns) - 1)) we multiply the gutter size with the amount of gutters

  3. var(--content-width) - ( var(--gutter) * (var(--columns) - 1)) ) We subtract the combined gutter size from the content width

  4. (var(--content-width) - (var(--gutter) * (var(--columns) - 1))) / var(--columns) we divide everything by the amount of columns.

We result in rows having the same height as the columns width.

Thanks for reading!

If you liked this, make sure to leave a heart.

If you want to see more of this, make sure to follow me on twitter and/or codepen

If you think there is something that can be improved or there is something you want to ask me please let me know in the comments.

Also thanks to @rachsmith for encouraging me to write about a pen.

4,826 2 71