CSS Justified Gallery Rows

A photo gallery where every row fills the width and photos keep their shape, like Flickr or Google Photos.

  • masonry
  • photo gallery
  • flex-grow
  • aspect-ratio
  • flickr
HTML
<div class="justified">
  <div style="--r: 1.5"></div>
  <div style="--r: 0.75"></div>
  <div style="--r: 1"></div>
  <div style="--r: 1.33"></div>
  <div style="--r: 1.78"></div>
  <div style="--r: 0.8"></div>
  <div style="--r: 1.2"></div>
</div>
CSS
/* --r is each photo's width / height ratio */
.justified {
  --row-height: 180px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.justified > * {
  flex: calc(var(--r) * 100) 1 calc(var(--r) * var(--row-height));
  aspect-ratio: var(--r);
}

.justified img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* Keeps the last row from stretching */
.justified::after {
  content: "";
  flex-grow: 1000000;
}

About this CSS Justified Gallery Rows

This CSS Justified Gallery Rows is 25 lines of pure CSS (0.4 KB) with no JavaScript and no dependencies. It uses Flexbox, aspect-ratio and custom properties. It works in current versions of Chrome, Edge, Safari and Firefox. It works in any stack: plain HTML, React, Vue, Svelte, Astro, WordPress or Webflow.

CSS features used

Customize it

Change these custom properties to restyle the justified gallery rows without touching the rest of the CSS:

PropertyDefault
--row-height180px

How to use this justified gallery rows

  1. Copy the HTML and paste it where you want the element to appear.
  2. Copy the CSS into your stylesheet, or inside a <style> tag.
  3. Keep the .justified class name, or rename it in both places. Then tweak colors, sizes and timing to match your design.
  4. Using React or Next.js? Change class to className in the HTML. The CSS works as is, including in Tailwind projects (put it in your global stylesheet).

Building with an AI tool?

“Copy for AI” copies a short prompt for Cursor, Claude Code, Lovable, Bolt or v0. Your AI tool opens the Markdown version of this snippet and reads the HTML, CSS and setup notes there. If your tool can't open links, with the code instead. More ways to use copy CSS with AI.

Feedback