DEV Community

Cover image for Items in, Columns out | Playing with CSS Grid
Milan Radojević
Milan Radojević

Posted on • Updated on

Items in, Columns out | Playing with CSS Grid

Intro

I'm starting a series on things you can do with css grid, and to start it off here's something simple.

The Idea

Just add items to a certain element and have them automatically ordered into columns (or rows) with CSS Grid.

Demo

How it works

There are really only three properties that we need to do this (everything else in the demo is just for looks). They are:

.parent_element {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-auto-rows: auto;
}
Enter fullscreen mode Exit fullscreen mode

So the first property tells the browser that the element with that class should behave like a grid.

The second property tells how many columns there should be.
repeat(7, 1fr) is just syntactic sugar for 1fr 1fr 1fr 1fr 1fr 1fr 1fr.
The fr is a css unit that means fraction, so this divides the element into 7 equal columns.

The third property is what tells the browser to handle setting the rows, and the value passed to it is what the row height should be.

If you want to order things into rows then just use:

.parent_element {
  display: grid;
  grid-template-rows: repeat(7, 1fr);
  grid-auto-columns: auto;
}
Enter fullscreen mode Exit fullscreen mode

Use cases

You'll use this method mostly when elements are all of the same (or at least similar) height. Here are some ideas where it can be useful:

  • Web Store Items, when you have a card that contains an item's picture, name and other properties, you can organise all of them into a neat grid
  • Portfolio projects, again cards, same concept as above
  • A calendar, if you ever need to put one on a website
  • Gallery, only if all pictures are the same height
  • Grid view on Dropbox/Google Drive - maybe you decide you want to build them from scratch for your portfolio

What not to use this for

  • Masonry layout (think of pintrest cards), why, because each row's height is the same as it's tallest member and there'll be weird white spaces everywhere, instead use columns property or multiple vertical flexboxes and divide elements between them

If you have any suggestions please let me know in the comments.

Top comments (0)