The 1K dynamic CSS-grid

TL;DR: CSS-grids and CSS-variables is the perfect match.

Grids have been used in graphic design for centuries, as a way to design and structure content. This have since spread into the web, and been implemented in a ton of frameworks with many different approaches. Most of these require either a ton of predefined wrapper classes, or a pre-processor to compile a bunch of mixins resulting in essentially the same markup.

Recently CSS-grids have been a huge trend as it has become available in all major browsers. And guess what.. so has CSS-variables!

This opens a ton of new possibility as it can oust pre-processors and generate truly clean and native markup. I’ve implemented a simple and dynamic grid-system that can replace all symmetric grid systems while feeling natural to use.

:root {
	--gw: 940px;
	--gg: 20px;
	--gc: 12;
	--x: auto;
	--y: auto;
	--w: 1;
	--h: 1;
.basegrid {
	--t: calc((var(--gw) + var(--gg)) / var(--gc) - var(--gg));
	width: var(--gw);
	display: grid;
	grid-template-columns: repeat(var(--gc), var(--t));
	grid-gap: var(--gg);
	grid-auto-flow: row dense;
.basegrid > div {
	grid-column: var(--x) / span var(--w);
	grid-row: var(--y) / span var(--h);

The above code is all you need. It has a set of predefined defaults, but can be overwritten dynamically on a grid to grid basis (using the same CSS).

To create a 1200px grid with 40px gap just overwrite as such:

<div class="grid" style="--gw: 1200px; --gg: 40px;">
	<div style="--w:4"></div>
	<div style="--w:4"></div>
	<div style="--w:4"></div>

Want 16 columns? Just set --gc: 16; and define your sections accordingly:

<div class="grid" style="--gc: 16">
	<div style="--w:8"></div>
	<div style="--w:8"></div>
	<div style="--w:16"></div>

This has massive benefits for file-size and markup complexity! Notice the whole thing is only one neasted div? And it’s so tiny it fits in a tweet!

Profile picture

Stefan Rasmussen (@okydk)

Full-stack developer and proud founder of and F117.