Workflow

Publishing layouts

How the photos are arranged on the page.

I’ve built different layouts for displaying my photos. When the site is built, each photo’s dimensions are written into the page, using the metadata created by the pipeline, so every layout can size every photo before it loads, and nothing shifts as the photos arrive.

Justified #

The justified layout is what I use for galleries, similar to Flickr and Google Photos. It’s built on top of a pure-CSS flexbox technique described by xieranmaya in this post.

The idea is to start every image at the same minimum height. Its width comes from its aspect ratio. The images are placed side by side, wrapping onto a new row when the next one doesn’t fit. Then flex-grow makes each one grow in proportion to its width, so the row fills the width at a single height. Each row gets its own height, depending on the photos in it. Aspect ratios are preserved, so photos are not cropped or stretched.

The minimum height decides how many images fit in a row, and each gallery can pick a smaller or larger one. Since the images only grow from there, rows end up a little taller than that.

A
B
C
D
E
1. Every photo gets the same height and its own width, and they're placed side by side. Photo E doesn't fit in the space left (hatched), so it starts the next row.
A
B
C
D
A
B
C
D
2. The space left over is split into shares in proportion to each photo's aspect ratio (its flex-grow): a 3:2 photo gets more than twice the share of a 2:3 one.
A
B
C
D
3. Each photo grows by its share and keeps its shape. Because the shares follow the widths, every photo grows by the same proportion, so the row reaches the edge at one height.
Show the codeHide the code

Here is the code for a simplified version of the justified layout, with CSS only. Each grey box stands for a photo, and --w and --h give its shape.

<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  /* The boxes sit side by side and wrap onto a new row when the next
     one doesn't fit. flex-start stops a box from stretching to the
     tallest in its row. The minimum height is a plain number because
     the calculations below turn it into pixels. */
  .gallery {
    --min-height: 260;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    gap: 12px;
  }

  /* Each box stands for a photo. --w and --h are its width and
     height, and only their ratio matters, so 3 and 2 work as well as
     1500 and 1000. */
  .photo {
    position: relative;
    aspect-ratio: var(--w) / var(--h);
    background: #e3e3e3;

    /* The box's width at the minimum height, as a plain number */
    --start-width: calc(var(--w) * var(--min-height) / var(--h));

    /* Start at that width */
    width: calc(var(--start-width) * 1px);

    /* Grow in proportion to it, so every box in a row grows by the
       same factor and the row stays one height */
    flex-grow: var(--start-width);

    /* Never shrink, so a box that doesn't fit wraps onto the next
       row instead */
    flex-shrink: 0;

    /* Keep a very wide photo inside the row */
    max-width: 100%;
  }

  /* If you put an <img> inside a box, it fills the box */
  .photo > img {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

<div class="gallery">
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
</div>

Last row #

The last row might have fewer images than a full row, and with flex-grow alone they would stretch across the whole width and end up much taller than the rows above. The original post solves this with an extra element at the end that takes up the space left, so the last row never grows: its images stay at the minimum height, shorter than the rows above, even when the row is almost full.

With flex-grow alone, the last row stretches across the whole width and ends up much taller than the row above.
With the original post's fix, an extra element takes the space left (hatched), and the last row stays at the minimum height, shorter than the row above.

While I always prefer CSS for layout, to keep the last row consistent with the rest of the grid, I added a script instead.

Once the images are laid out, the script decides whether the last row is justified like the others or matches the height of the row above. To decide, it sizes the last row like the row above and checks how much of the width it fills:

  • Less than 80%: the images keep the height of the row above, and the rest of the row stays empty.
  • At least 80%: the images grow to fill the width. They end up at most about a quarter taller than the row above.

There’s no formula behind 80%. It’s simply where the last row looked right to me.

At the height of the row above, the last row would fill 41% of the width.
That's less than 80%, so it keeps that height, and the rest stays empty.
At the height of the row above, the last row would fill 82% of the width.
That's at least 80%, so it grows to fill the width.

When the window is resized, the browser wraps and grows the rows again on its own, and the script runs the last-row check again, at most once per frame. It works out the rows from the image sizes it already knows instead of measuring the page.

A
B
C
D
E
F
G
H
I
J
K
L
Show the codeHide the code

Here is the code for a simplified version of the justified layout, including the last row. Each grey box stands for a photo, and --w and --h give its shape.

<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  /* The boxes sit side by side and wrap onto a new row when the next
     one doesn't fit. flex-start stops a box from stretching to the
     tallest in its row. The minimum height is a plain number because
     the calculations below turn it into pixels. If you change it or
     the gap, change MIN_HEIGHT and GAP in the script too. */
  .gallery {
    --min-height: 260;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    gap: 12px;
  }

  /* Each box stands for a photo. --w and --h are its width and
     height, and only their ratio matters, so 3 and 2 work as well as
     1500 and 1000. */
  .photo {
    position: relative;
    aspect-ratio: var(--w) / var(--h);
    background: #e3e3e3;

    /* The box's width at the minimum height, as a plain number */
    --start-width: calc(var(--w) * var(--min-height) / var(--h));

    /* Start at that width */
    width: calc(var(--start-width) * 1px);

    /* Grow in proportion to it, so every box in a row grows by the
       same factor and the row stays one height */
    flex-grow: var(--start-width);

    /* Never shrink, so a box that doesn't fit wraps onto the next
       row instead */
    flex-shrink: 0;

    /* Keep a very wide photo inside the row */
    max-width: 100%;
  }

  /* If you put an <img> inside a box, it fills the box */
  .photo > img {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  /* The script adds this class to the boxes of a mostly empty last
     row. They stop growing and take the height of the row above,
     which the script passes in as --cap-height. */
  .photo.capped {
    flex-grow: 0;
    --min-height: var(--cap-height);
  }
</style>

<div class="gallery">
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
</div>

<script>
  // The same minimum height and gap as in the CSS
  const MIN_HEIGHT = 260;
  const GAP = 12;

  // If the last row would fill less than this share of the width, it
  // keeps the height of the row above instead of growing
  const FILL_THRESHOLD = 0.8;

  const gallery = document.querySelector('.gallery');

  // Reads a number such as --w from a box's style attribute
  function read(element, name) {
    return Number(element.style.getPropertyValue(name));
  }

  // Every box with its shape, and its width at the minimum height
  const photos = [...gallery.children].map(element => {
    const w = read(element, '--w');
    const h = read(element, '--h');
    return { element, w, h, startWidth: w * MIN_HEIGHT / h };
  });

  // Splits the boxes into rows the same way the browser does. A box
  // joins the current row if it fits, or starts a new row.
  function splitIntoRows(galleryWidth) {
    const rows = [[]];
    let rowWidth = 0;

    for (const photo of photos) {
      const row = rows[rows.length - 1];

      // A box needs its own width, plus a gap if the row isn't empty
      const needed = photo.startWidth + (row.length > 0 ? GAP : 0);

      if (row.length > 0 && rowWidth + needed > galleryWidth) {
        rows.push([photo]);
        rowWidth = photo.startWidth;
      } else {
        row.push(photo);
        rowWidth += needed;
      }
    }
    return rows;
  }

  // The height a row reaches once its boxes have grown to fill the
  // width. Every box grows by the same factor, and so does the row.
  function grownHeight(row, galleryWidth) {
    let rowStartWidth = 0;
    for (const photo of row) rowStartWidth += photo.startWidth;

    const gaps = (row.length - 1) * GAP;
    return MIN_HEIGHT * (galleryWidth - gaps) / rowStartWidth;
  }

  // Lets the last row grow like the others, or keeps it at the height
  // of the row above when it's mostly empty
  function updateLastRow() {
    const galleryWidth = gallery.getBoundingClientRect().width;
    const rows = splitIntoRows(galleryWidth);
    const lastRow = rows[rows.length - 1];
    let capHeight = 0;

    if (rows.length > 1) {
      const rowAbove = rows[rows.length - 2];
      const heightAbove = grownHeight(rowAbove, galleryWidth);

      // How wide the last row would be at that height, gaps included
      let lastRowWidth = (lastRow.length - 1) * GAP;
      for (const photo of lastRow) {
        lastRowWidth += photo.w * heightAbove / photo.h;
      }

      if (lastRowWidth < galleryWidth * FILL_THRESHOLD) {
        capHeight = heightAbove;
      }
    }

    // The .capped rule in the CSS stops these boxes from growing and
    // gives them the height in --cap-height
    for (const photo of photos) {
      const capped = capHeight > 0 && lastRow.includes(photo);
      photo.element.classList.toggle('capped', capped);
      photo.element.style.setProperty('--cap-height', capHeight);
    }
  }

  // Run it now, so the page never shows a stretched last row, and
  // again whenever the window changes size
  updateLastRow();
  window.addEventListener('resize', updateLastRow);
</script>

Pattern #

I built the pattern layout for the journal. It follows a structure of rows that I write each time I use it. A row is a list of numbers, one per column, each saying how many photos that column stacks. For example, 2 1 is two columns, with two photos stacked on the left and one on the right. The photos fill the rows in order, and the pattern starts again from the first row when there are more photos.

When the site is built, each column’s width is worked out so that all the columns in a row end at the same height, and every photo keeps its aspect ratio:

A
B
C
2 1 at equal widths, then with the widths worked out, so the columns end level. Column widths: 32%, 68%
A
B
C
D
1 1 2 at equal widths, then with the widths worked out, so the columns end level. Column widths: 23%, 52%, 24%

A row can have any number of columns, and a column can stack any number of photos, so there are plenty of possibilities. Here are a few:

1 1 1: three columns, with 1 photo each.
1 1 2: three columns, with 1, 1, and 2 photos.
2 1: two columns, with 2 and 1 photos.
2 2: two columns, with 2 photos each.
1 2 1: three columns, with 1, 2, and 1 photos.
1 3: two columns, with 1 and 3 photos.
2 1 1 and 1 1 2, one after another.
1 1 1 and 1 2 1, then 1 1 1 again as the pattern starts over.
Show the codeHide the code

Here is the code for a simplified version of the pattern layout. The site works out the column widths when it’s built. In this version, a few lines of JavaScript do the same, so you can change the rows and boxes and the columns still end at the same height.

<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  /* The pattern stacks its rows, each row puts its columns side by
     side, and each column stacks its boxes. If you change the gap,
     change GAP in the script too. */
  .pattern {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .row {
    display: flex;
    gap: 12px;
  }

  .column {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  /* Each box stands for a photo, and --w and --h are its width and
     height. The box keeps that shape at any width. */
  .photo {
    position: relative;
    aspect-ratio: var(--w) / var(--h);
    background: #e3e3e3;
  }

  /* If you put an <img> inside a box, it fills the box */
  .photo > img {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

<div class="pattern">
  <!-- Row 2 1, two boxes stacked on the left and one on the right -->
  <div class="row">
    <div class="column">
      <div class="photo" style="--w: 3; --h: 2"></div>
      <div class="photo" style="--w: 3; --h: 2"></div>
    </div>
    <div class="column">
      <div class="photo" style="--w: 2; --h: 3"></div>
    </div>
  </div>

  <!-- Row 1 1 1, one box in each of three columns -->
  <div class="row">
    <div class="column">
      <div class="photo" style="--w: 2; --h: 3"></div>
    </div>
    <div class="column">
      <div class="photo" style="--w: 3; --h: 2"></div>
    </div>
    <div class="column">
      <div class="photo" style="--w: 2; --h: 3"></div>
    </div>
  </div>
</div>

<script>
  // The same gap as in the CSS
  const GAP = 12;

  // Reads a number such as --w from a box's style attribute
  function read(element, name) {
    return Number(element.style.getPropertyValue(name));
  }

  for (const row of document.querySelectorAll('.row')) {
    // For each column, its relative height (how tall its boxes are
    // for every pixel of width, all added up) and how many gaps there
    // are between them. A column w pixels wide is then
    // w * relativeHeight + gaps * GAP tall.
    const columns = [...row.children].map(element => {
      const photos = [...element.children];
      let relativeHeight = 0;
      for (const photo of photos) {
        relativeHeight += read(photo, '--h') / read(photo, '--w');
      }
      return { element, relativeHeight, gaps: photos.length - 1 };
    });

    // Two things must hold. Every column ends at the same height:
    //   height = width * relativeHeight + gaps * GAP
    // and the columns plus the gaps between them fill the row:
    //   sum of widths + columnGaps * GAP = row width
    // Solving for each column's width gives a share of the row
    // plus a fixed number of pixels, which CSS calc() can use at
    // any width.
    let shareTotal = 0;
    let gapTotal = 0;
    for (const column of columns) {
      shareTotal += 1 / column.relativeHeight;
      gapTotal += column.gaps / column.relativeHeight;
    }
    const columnGaps = columns.length - 1;

    for (const column of columns) {
      const share = 1 / (shareTotal * column.relativeHeight);
      const gapCount = (gapTotal - columnGaps) * share
        - column.gaps / column.relativeHeight;
      const pixels = gapCount * GAP;
      const width = `calc(${share} * 100% + ${pixels}px)`;
      column.element.style.width = width;
    }
  }
</script>

Masonry #

I built the masonry layout for the journal too. Like Pinterest’s, it stacks photos in columns, and each photo takes the full width of its column, so it favours portraits.

In the classic version, every column has the same width. The simplest way to build it is CSS only, with the photos running down each column. A script can put each photo into the shortest column instead, so they run across. Either way, each column ends at its own height, so the bottom of the gallery is uneven:

A
B
C
D
E
F
G
H
With CSS only, the photos run down each column in order, and the browser evens out the heights as best it can.
A
B
C
D
E
F
G
H
With a script, each photo goes into the shortest column, in order.
Show the codeHide the code

Here is the code for simplified versions of both. Each shows two columns on small screens, three from 640px wide, and four from 1024px. With CSS only:

<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  /* The browser splits the boxes into columns of the same width,
     filling each column from top to bottom before starting the next.
     Two columns fit small screens. */
  .masonry {
    columns: 2;
    column-gap: 12px;
  }

  /* Three columns from 640px wide, and four from 1024px */
  @media (min-width: 640px) {
    .masonry {
      columns: 3;
    }
  }

  @media (min-width: 1024px) {
    .masonry {
      columns: 4;
    }
  }

  /* Each box stands for a photo, and --w and --h are its width and
     height. The box keeps that shape at the column's width. It sits
     on its own line (inline-block at full width), so the browser
     moves it to the next column whole, gap included, and never
     splits it. That works like break-inside: avoid, and also keeps
     the gap with its box. vertical-align: top removes the space
     inline boxes leave underneath. */
  .photo {
    display: inline-block;
    position: relative;
    width: 100%;
    aspect-ratio: var(--w) / var(--h);
    margin-bottom: 12px;
    vertical-align: top;
    background: #e3e3e3;
  }

  /* If you put an <img> inside a box, it fills the box */
  .photo > img {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

<div class="masonry">
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
</div>

With a script that moves each box into the shortest column:

<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  /* The columns sit side by side, all the same width, and each one
     stacks its boxes. The script moves every box into a column. */
  .masonry {
    display: flex;
    align-items: flex-start;
    gap: 12px;
  }

  /* flex: 1 gives every column the same width, and min-width: 0 lets
     a column be narrower than what's inside it */
  .column {
    display: flex;
    flex: 1;
    flex-direction: column;
    gap: 12px;
    min-width: 0;
  }

  /* Each box stands for a photo, and --w and --h are its width and
     height. The box keeps that shape at the column's width. */
  .photo {
    position: relative;
    aspect-ratio: var(--w) / var(--h);
    background: #e3e3e3;
  }

  /* If you put an <img> inside a box, it fills the box */
  .photo > img {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

<div class="masonry">
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
</div>

<script>
  const masonry = document.querySelector('.masonry');
  const photos = [...masonry.querySelectorAll('.photo')];

  // How many columns fit: two on small screens, three from 640px
  // wide, and four from 1024px
  function columnCount() {
    if (window.matchMedia('(min-width: 1024px)').matches) return 4;
    if (window.matchMedia('(min-width: 640px)').matches) return 3;
    return 2;
  }

  // Puts every box, in order, into whichever column is shortest at
  // that moment. The columns are measured as they fill, so the gaps
  // between boxes count too.
  function layOut() {
    const count = columnCount();
    const columns = [];
    for (let i = 0; i < count; i++) {
      const column = document.createElement('div');
      column.className = 'column';
      columns.push(column);
    }
    masonry.replaceChildren(...columns);

    for (const photo of photos) {
      let shortest = columns[0];
      let shortestHeight = Infinity;
      for (const column of columns) {
        const height = column.getBoundingClientRect().height;
        if (height < shortestHeight) {
          shortest = column;
          shortestHeight = height;
        }
      }
      shortest.append(photo);
    }
  }

  // Lay the boxes out now, and again whenever the window changes
  // size, since a different width can change which column is shortest
  layOut();
  window.addEventListener('resize', layOut);
</script>

Level bottom #

A level bottom is possible, though, if each column gets its own width. The approach I use, the second one below, places the tallest photos first, and works out the columns and their widths when the site is built, from each photo’s dimensions. How much the widths change depends on which column each photo goes into:

A
B
C
D
E
F
G
H
Placed as before, each photo into the shortest column, with the widths solved. The bottom is level, with different column widths. Column widths: 25%, 32%, 43%
A
B
C
D
E
F
G
H
Tallest photos first, each into the shortest column, then back in order. With the widths solved, the bottom is level and the column widths are more balanced. Column widths: 34%, 34%, 33%
Show the codeHide the code

Here is the code for both. They work like the ones above, with the same number of columns at each width, but also work out each column’s width the way the pattern layout does, so the columns end level. With each box placed in the shortest column, as before:

<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  /* The columns sit side by side and each one stacks its boxes. The
     script splits the boxes into columns and works out each column's
     width. If you change the gap, change GAP in the script too. */
  .masonry {
    display: flex;
    align-items: flex-start;
    gap: 12px;
  }

  .column {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  /* Each box stands for a photo, and --w and --h are its width and
     height. The box keeps that shape at the column's width. */
  .photo {
    position: relative;
    aspect-ratio: var(--w) / var(--h);
    background: #e3e3e3;
  }

  /* If you put an <img> inside a box, it fills the box */
  .photo > img {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

<div class="masonry">
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
</div>

<script>
  // The same gap as in the CSS
  const GAP = 12;

  const masonry = document.querySelector('.masonry');

  // Reads a number such as --w from a box's style attribute
  function read(element, name) {
    return Number(element.style.getPropertyValue(name));
  }

  // Every box with its relative height, which is how tall it is for
  // every pixel of width
  const boxes = masonry.querySelectorAll('.photo');
  const photos = [...boxes].map(element => {
    const w = read(element, '--w');
    const h = read(element, '--h');
    return { element, relativeHeight: h / w };
  });

  // How many columns fit: two on small screens, three from 640px
  // wide, and four from 1024px
  function columnCount() {
    if (window.matchMedia('(min-width: 1024px)').matches) return 4;
    if (window.matchMedia('(min-width: 640px)').matches) return 3;
    return 2;
  }

  // Puts each box, in order, into the shortest column so far, like
  // the shortest column sample above, but adding up relative heights
  // instead of measuring the columns. With fewer boxes than columns,
  // the empty columns are left out.
  function split(count) {
    const columns = [];
    for (let i = 0; i < count; i++) {
      columns.push({ photos: [], relativeHeight: 0 });
    }

    for (const photo of photos) {
      let shortest = columns[0];
      for (const column of columns) {
        if (column.relativeHeight < shortest.relativeHeight) {
          shortest = column;
        }
      }
      shortest.photos.push(photo);
      shortest.relativeHeight += photo.relativeHeight;
    }
    return columns.filter(column => column.photos.length > 0);
  }

  // Splits the boxes into columns, works out each column's width, and
  // rebuilds the page
  function layOut() {
    const columns = split(columnCount());

    // Two things must hold. Every column ends at the same height:
    //   height = width * relativeHeight + gaps * GAP
    // and the columns plus the gaps between them fill the gallery:
    //   sum of widths + columnGaps * GAP = gallery width
    // Solving for each column's width gives a share of the gallery
    // plus a fixed number of pixels, which CSS calc() can use at
    // any width.
    let shareTotal = 0;
    let gapTotal = 0;
    for (const column of columns) {
      const gaps = column.photos.length - 1;
      shareTotal += 1 / column.relativeHeight;
      gapTotal += gaps / column.relativeHeight;
    }
    const columnGaps = columns.length - 1;

    const columnElements = columns.map(column => {
      const gaps = column.photos.length - 1;
      const share = 1 / (shareTotal * column.relativeHeight);
      const gapCount = (gapTotal - columnGaps) * share
        - gaps / column.relativeHeight;
      const pixels = gapCount * GAP;
      const width = `calc(${share} * 100% + ${pixels}px)`;

      const element = document.createElement('div');
      element.className = 'column';
      element.style.width = width;
      element.append(...column.photos.map(photo => photo.element));
      return element;
    });
    masonry.replaceChildren(...columnElements);
  }

  // Split the boxes now, and again when the number of columns
  // changes. In between, the widths in calc() keep the columns level.
  layOut();
  for (const query of ['(min-width: 640px)', '(min-width: 1024px)']) {
    window.matchMedia(query).addEventListener('change', layOut);
  }
</script>

With the tallest boxes placed first, each into the shortest column:

<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  /* The columns sit side by side and each one stacks its boxes. The
     script splits the boxes into columns and works out each column's
     width. If you change the gap, change GAP in the script too. */
  .masonry {
    display: flex;
    align-items: flex-start;
    gap: 12px;
  }

  .column {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  /* Each box stands for a photo, and --w and --h are its width and
     height. The box keeps that shape at the column's width. */
  .photo {
    position: relative;
    aspect-ratio: var(--w) / var(--h);
    background: #e3e3e3;
  }

  /* If you put an <img> inside a box, it fills the box */
  .photo > img {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

<div class="masonry">
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
  <div class="photo" style="--w: 3; --h: 2"></div>
  <div class="photo" style="--w: 2; --h: 3"></div>
</div>

<script>
  // The same gap as in the CSS
  const GAP = 12;

  const masonry = document.querySelector('.masonry');

  // Reads a number such as --w from a box's style attribute
  function read(element, name) {
    return Number(element.style.getPropertyValue(name));
  }

  // Every box with its place in the original order and its relative
  // height, which is how tall it is for every pixel of width
  const boxes = masonry.querySelectorAll('.photo');
  const photos = [...boxes].map((element, index) => {
    const w = read(element, '--w');
    const h = read(element, '--h');
    return { element, index, relativeHeight: h / w };
  });

  // How many columns fit: two on small screens, three from 640px
  // wide, and four from 1024px
  function columnCount() {
    if (window.matchMedia('(min-width: 1024px)').matches) return 4;
    if (window.matchMedia('(min-width: 640px)').matches) return 3;
    return 2;
  }

  // Splits the boxes into columns that hold about the same. The
  // tallest boxes go first, each into the shortest column so far.
  // Each column then keeps its boxes in their original order. With
  // fewer boxes than columns, the empty columns are left out.
  function split(count) {
    const columns = [];
    for (let i = 0; i < count; i++) {
      columns.push({ photos: [], relativeHeight: 0 });
    }

    const tallestFirst = [...photos]
      .sort((a, b) => b.relativeHeight - a.relativeHeight);
    for (const photo of tallestFirst) {
      let shortest = columns[0];
      for (const column of columns) {
        if (column.relativeHeight < shortest.relativeHeight) {
          shortest = column;
        }
      }
      shortest.photos.push(photo);
      shortest.relativeHeight += photo.relativeHeight;
    }

    // Boxes in their original order, and columns in the order of
    // their first box
    const filled = columns.filter(column => column.photos.length > 0);
    for (const column of filled) {
      column.photos.sort((a, b) => a.index - b.index);
    }
    const first = column => column.photos[0].index;
    return filled.sort((a, b) => first(a) - first(b));
  }

  // Splits the boxes into columns, works out each column's width, and
  // rebuilds the page
  function layOut() {
    const columns = split(columnCount());

    // Two things must hold. Every column ends at the same height:
    //   height = width * relativeHeight + gaps * GAP
    // and the columns plus the gaps between them fill the gallery:
    //   sum of widths + columnGaps * GAP = gallery width
    // Solving for each column's width gives a share of the gallery
    // plus a fixed number of pixels, which CSS calc() can use at
    // any width.
    let shareTotal = 0;
    let gapTotal = 0;
    for (const column of columns) {
      const gaps = column.photos.length - 1;
      shareTotal += 1 / column.relativeHeight;
      gapTotal += gaps / column.relativeHeight;
    }
    const columnGaps = columns.length - 1;

    const columnElements = columns.map(column => {
      const gaps = column.photos.length - 1;
      const share = 1 / (shareTotal * column.relativeHeight);
      const gapCount = (gapTotal - columnGaps) * share
        - gaps / column.relativeHeight;
      const pixels = gapCount * GAP;
      const width = `calc(${share} * 100% + ${pixels}px)`;

      const element = document.createElement('div');
      element.className = 'column';
      element.style.width = width;
      element.append(...column.photos.map(photo => photo.element));
      return element;
    });
    masonry.replaceChildren(...columnElements);
  }

  // Split the boxes now, and again when the number of columns
  // changes. In between, the widths in calc() keep the columns level.
  layOut();
  for (const query of ['(min-width: 640px)', '(min-width: 1024px)']) {
    window.matchMedia(query).addEventListener('change', layOut);
  }
</script>

Grid #

The grid arranges photos in columns of equal cells, square by default. It can have two, three, or four columns, and the cells can take another shape. Every photo is cropped to fit its cell. I rarely want my photos cropped, so I haven’t used it yet.

2 columns.
3 columns.
4 columns.
Show the codeHide the code

Here is the code for a simplified version of the grid layout. The grid shows two columns on small screens and three from 1024px wide. Change --w and --h to give the cells a different shape.

<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  /* --w and --h set the shape of every cell. 1 and 1 makes them
     square, and 4 and 3 would make them landscape. Two columns fit
     small screens. minmax(0, 1fr) keeps the columns equal even if
     something inside one is wider. */
  .grid {
    --w: 1;
    --h: 1;
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
  }

  /* Three columns from 1024px wide */
  @media (min-width: 1024px) {
    .grid {
      grid-template-columns: repeat(3, minmax(0, 1fr));
    }
  }

  /* Each box stands for a photo, in the shape of the cell */
  .photo {
    position: relative;
    aspect-ratio: var(--w) / var(--h);
    background: #e3e3e3;
  }

  /* If you put an <img> inside a box, it covers the cell, and
     whatever doesn't match the cell's shape is cropped */
  .photo > img {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

<div class="grid">
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
</div>