CSS grid responsive cards

Word count icon

284 words

Reading time icon

1 minutes

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...

React icon
margin: '2em auto',
display: 'grid',
gridAutoRows: 'auto',
gridTemplateColumns: 'repeat(auto-fill, minmax(auto, 450px))',
gap: '1.5em',
justifyContent: 'space-evenly',
width: '100%',
{projects.map(({ node: project }) => (
<ProjectCard key={project.id} {...project} />

Can you spot the magic line?

React icon
gridTemplateColumns: '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!) 😃