CSS Grid — Responsive layouts and components
Let’s make a photo gallery responsive quickly and using very few lines of CSS.
--
Hello again! 👋 Today we’re going to talk about how to build responsive layouts while using CSS Grid. If you’re just starting with Grid, I recommend that you read my first blogpost before this one. Baby steps!
In this post, we’re going to build a photo gallery (on our fictional social network for dogs) and I’m going to show you how I organize responsive layouts in two different scenarios:
- Layouts with repeating components;
- And how to make a component itself responsive.
Of course we’re sticking with puppies, so let me introduce Pady, Lola’s brother. 🐶 He’s quite helpful when he’s not too busy trying to eat his toys, so here he is:
Without further ado, let’s dive into those layouts.
Layouts with repeating components
You know the drill. The first thing you have to do is setup your grid with display: grid;
so you can start working on it.
The HTML structure for the gallery is a div
, the container where we’ll set the grid properties. Inside, several div
items with images inside (so we can see the cells well).
As you can see on the preview above, we have a grid with one column and a gap with 10px. The items on the grid get their heights from the images inside them, and when needed will stretch to occupy the full grid width.
When it comes to alignments, the default value is always to stretch (whether we’re talking about grid items, grid tracks or the grid itself). You can change this with properties that are very similar to the ones used with CSS Flexbox. We’re not going to explore that here, but you can check CSS Tricks Guide to Grid, which explains this in a very organized and visual way!
For now, let’s give images 100% width and we’ll deal with them once our grid is all set up.