How to create a flexible square grid with CSS Grid Layout

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.