Author: Richard Haines

Posted: 07 Apr 2020

take me there

  • Responsive cards with css grid.

Responsive cards with css grid.

Whenever we want to display a bunch of cards on a page we want them to be responsive. We want the columns and rows to be dynamic depending on the screen width. To that end we could add a bunch of media queries to our code and be done with it. However, css grid makes this easy for us and without the need for media queries.

There are many hundreds of articles out there in on the internet that explain this very concept. Im writing this post more as a reminder to myself as i always find myself forgetting the syntax and having to pull up other projects which i have used it in. Which i slowly becoming basically all of them.

Lets say we have a container, this container will define our grid. Inside our container we have our card components which will be iterated over and displayed in a nice, responsive grid. Lets gooooo...

1<div
2 sx={{
3 margin: "2em auto",
4 display: "grid",
5 gridAutoRows: "auto",
6 gridTemplateColumns: "repeat(auto-fill, minmax(auto, 450px))",
7 gap: "1.5em",
8 justifyContent: "space-evenly",
9 width: "100%"
10 }}
11 >
12 {projects.map(({ node: project }) => (
13 <ProjectCard
14 key={project.id}
15 {...project}
16 />
17 ))}
18 </div>

Can you spot the magic line?

1gridTemplateColumns: "repeat(auto-fill, minmax(auto, 450px))"

Here we are telling the grid template columns property that depending on the amount of iterated components we want, to auto fill each column by how ever many components there are. The second argument is a minmax function which is saying that at their smallest the cards should have an auto width (this can be set to anything lower than the second param, which is the largest width) and at their largest they should have no more than 450px width. The repeat function which takes this information ensures that the end result is dynamic by repeating its input for as many iterables as there are.

You are welcome future me (any anyone else who finds this helpful!) 😃

Edit on GitHub.Previous: Text with linear gradient backgroundNext: Add Theme-ui to Next