This article utilizes React, but the techniques are frontend-agnostic.

Dynamic, Fractal Image Grids Within Constant-sized Containers

Image for post
Image for post

While working on a recent project, I needed to implement a CMS for an image gallery. In this gallery, multiple images may belong to the same item on display. I wireframed a handful of ideas, ultimately deciding that a compact layout, styled after the gallery itself, would be best. To achieve this, I turned to mathematics to create dynamic, fractal image grids within constant-sized containers.

Image for post
Image for post

To begin with, I created a standard grid to hold my cards. A dissection of CSS Grid is beyond the scope of this article, but a functional component follows.

We now have a functional grid of empty cards.

Image for post
Image for post

The Idea

Our goal is to dynamically fill each card with a varying number of images in a consistent pattern. To fit them, we’ll need to shrink the images based on the total number present. How do we approach this? I began with pencil and paper.

Image for post
Image for post

Let’s clean that up and map out the relationships.

Image for post
Image for post

Common Exponents

Though there are different bases, we can see that the properties of our grids share a common exponent based on the number of images present. We can calculate this common exponent by taking the log₄ of the number of images and rounding up. For example:

We now have all the information we need to dynamically adjust our grid.

Grid Setup

First, we handle the width of the cells. We know how many columns we will need based on how many cells-per-side we’ve calculated

We could similarly use grid-template-rows to set our rows, but this will create empty rows that will affect vertical alignment. Instead, we can use grid-auto-rows and distribute the fractional value across our cells-per-side.

All that remains is to add our images; and with that, we have a functioning, fractal grid.

Image for post
Image for post

If we aren’t concerned with maintaining aspect ratios, and we’d instead prefer to fill the available space, we can set grid-auto-rows to 1fr.

Image for post
Image for post

Epilogue

A fully functioning repository of the code in this article may be found at

A demonstration of the originating project may be viewed here:

Full stack web developer with a passion for number theory and algorithms.

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