An awesome yet simple grid made with CSS Grid

Per Jansson
3 min readFeb 1, 2018

--

Photo by Adarsh Kummur on Unsplash

Is CSS Grid Layout the best thing since sliced bread? Possibly! It used to be really hard to do layout of columns and rows while still keeping a good separation of concerns between markup and style. Until CSS Grid came and changed that by offering the possibility to apply CSS rules to both the parent element and the child elements. I will show you how little code is actually needed to create a responsive grid layout with a fancy twist.

First version

The site is showing a bunch of hamburger pictures, because who doesn’t like a really, really good hamburger, right?

The HTML is simply an unordered list:

The first version will be laying out the elements in a simple grid, meaning each burger image gets equal space. It will look like this:

The CSS to achieve this:

Only styling on parent element is needed. The list should display as a grid, there should be a small gap between rows and columns, three columns with equal space each and as many rows as needed is created with 40% height. Pretty straightforward and to be frank a bit boring.

Second version

Let’s spice things up by making some images higher, some wider and some bigger. It will look like this:

We also want it to be responsive, so it looks good on medium devices:

And small devices:

So how can we achieve this? Well, it’s gonna require some styling on both the parent element and the child elements.

First lets add style classes on the markup to tell which images should be high, which should be wide and which should be both:

And then update the CSS:

Boom! With that little code we have responsive grid layout with support for images of different sizes. Amazing!

But what the heck are we doing here? Lets look at the changes one by one:

grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))

Create as many columns that can fit one a row and let each grid item, i.e. the burger image, take equal amount of space but don’t shrink below 250px in width. If screen size is changed so an image does not fit on a given row it automatically wraps to the next row.

grid-auto-flow: dense

This one tells which algorithm the browser should use when specifying how items can be auto-placed in the grid. By using “dense” packing algorithm we instruct the browser to attempt to fill in holes earlier in the grid, which is exactly what we need since certain images are bigger than other and we don’t want any holes in our grid.

grid-column: span 2 and grid-row: span 2

Instructions to each grid element how many columns or rows they should span, which is how we make certain images twice as wide and/or high.

And finally, the best thing, it works in all real browsers :)

--

--

Per Jansson

Curious and impatient developer that loves to build great stuff and help others do the same.