How to create a flexible square grid with CSS Grid Layout

Kryštof Korb
Feb 9, 2018 · 1 min read

I'm sure every front-end developer has already heard about CSS Grid Layout. But if no, go and learn it by playing the amazing Grid Garden game and/or watch Rachel Andrew's talk from WebExpo 2017.

I was struggling with creating flexible full-viewport-width square grid defined by the the square size (if you want fixed number of columns it's much easier to go with vw units). Unfortunately this is something that display: grid; doesn't help much with, but thanks to one Rachel's post and some answers on Stack Overflow, I came up with a hackish, but simple and working solution.

The trick is to add an invisible square element (zero width and 100% bottom padding) to the grid, set equal height to all rows by grid-auto-rows: 1fr; and then reposition the invisible grid element as well as the first grid element to overlap.

Voilà! Try the pen and resize the window. Unfortunately this is not working in Firefox and possibly other browsers too, so consider it more as a little experiment than production-ready code.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store