Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 139 ยท Layout Fundamentals

Image Galleries and Masonry-style Layouts

Build galleries in CSS: uniform grids, justified flex rows, column-based masonry and spanning grids, plus where native masonry and grid-lanes stand.

A gallery looks easy until the pictures have different shapes. Wide landscapes, tall portraits and squares all want to live in the same grid. Squeeze them into identical boxes and you crop faces and skylines. Let them keep their shapes and you get ragged gaps. The famous answer is the masonry layout, where items of different heights pack tightly into columns, like bricks in a wall.

CSS has never had a finished, universally supported masonry mode, but it does have several good techniques, each with different trade-offs, and a native solution is being standardized. This lesson walks through the recipes you can use today, tells you how to choose between them, and explains where the new native feature stands.

All demos use colored tiles of different heights, generated by a little script, so no image files are needed. In real galleries the tiles would be <img> elements; see Styling Images and object-fit for sizing them.

Layout Ordering Gaps Best for
Uniform grid Left to right, row by row Cropped to equal cells Thumbnails, product lists
Justified rows Left to right, row by row None (rows fill the width) Photo albums like a magazine spread
Columns masonry Top to bottom within each column None Pins, notes, cards of varied height
Spanning grid Left to right with row spans Few, controlled Editorial or "featured" layouts

The ordering row matters for accessibility and for users: whatever you choose, make sure the DOM order still matches the order you want keyboard and screen reader users to follow.

Recipe 1: the uniform grid

The simplest gallery forces every cell to the same shape and crops the pictures. repeat(auto-fill, minmax(...)) makes the number of columns responsive without media queries, and aspect-ratio with object-fit: cover keeps each picture tidy.

CSS
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr));
  gap: 0.5rem;
}
.gallery img {
  width: 100%;
  aspect-ratio: 4 / 3;
  object-fit: cover;
}

Choose it when consistency matters more than showing each full picture. Details in Grid Patterns.

Recipe 2: justified rows with flexbox

Photo sites often show rows where every picture has the same height and the row stretches to the full width. Flexbox can do it if each item's flex-grow matches its aspect ratio. The trick: set flex: <ratio> and a base height, and let the pictures keep their natural shape with object-fit.

Justified rows with flex-grow

Resize the preview. Tiles keep roughly equal heights, rows fill the width, and wider pictures get wider tiles. The empty ::after with a huge flex-grow swallows spare space on the last row so it does not stretch awkwardly. With real images, add img { width: 100%; height: 100%; object-fit: cover; } inside each tile and put the aspect ratio in --ratio (for example from width / height attributes).

Recipe 3: columns-based masonry

CSS multi-column layout is the oldest and simplest masonry technique. The browser flows content into balanced columns, so tiles of any height pack tightly. You met it in Multi-column Layout.

Masonry with CSS columns

Look at the numbers: the order runs down the first column, then down the second, not across. For image walls, that is usually acceptable. For lists where the sequence matters (search results, a feed read in order, tab order), it is not: a keyboard user tabbing through the tiles jumps from the bottom of one column to the top of the next, which can be confusing.

Tips for columns masonry:

  • Always use break-inside: avoid (plus the older -webkit-column-break-inside if you need it) so a tile never splits.
  • Use column-width for responsive columns and column-count for a fixed number.
  • Use bottom margins on the tiles for vertical spacing: row-gap has no effect in multi-column layouts.
  • The browser balances columns, so there is no "load more" at the bottom that keeps columns even. Appending items can reshuffle everything.

Recipe 4: spanning grid ("dense" layouts)

When you control the content, such as a curated portfolio, CSS Grid can express tall and wide tiles directly. Define small rows, let each tile span several of them with grid-row: span N, and add grid-auto-flow: dense so later items fill earlier holes.

A grid with spanning tiles

This is a fixed-row-unit trick: every tile's height is a multiple of 40 px (plus the gaps), so the tiles interlock. It works for items with known shapes, such as a portfolio, but not for unknown content: you would need JavaScript to measure each item and set its span. Also note that dense places items out of source order to fill holes. This creates the same keyboard-order mismatch as columns, so use it only for non-sequential content.

Native masonry: where it stands

The CSS Working Group has been defining a true masonry layout. Items are placed in the columns with the most room, tracks on the other axis are free to differ in size, and the visual order stays close to the DOM order. Two syntaxes have been explored: a masonry value for grid-template-rows (prototyped in Firefox behind a flag) and a separate display value, display: grid-lanes, proposed by WebKit. The final name and properties may change, and as of now it is experimental in some browsers and absent in others.

CSS
/* Experimental: syntax and support are still settling */
.gallery {
  display: grid-lanes;
  grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr));
  gap: 8px;
}

What to do today:

  1. Build with a technique above (usually columns or a spanning grid) so every user gets a good layout.
  2. Layer native masonry as an enhancement in an @supports block only if you have tested the browsers that implement it. See Feature Queries.
  3. Check current browser compatibility before relying on any experimental feature.
CSS
@supports (display: grid-lanes) {
  .gallery { display: grid-lanes; columns: unset; }
}

Choosing a recipe

  • Order does not matter, items vary in height (inspiration boards, photo walls): columns masonry.
  • Order matters, sizes are roughly similar: a uniform grid with object-fit: cover.
  • A photo album with whole pictures and an even edge: justified flex rows.
  • Editorial tiles you design by hand: spanning grid with dense flow.
  • Thousands of items: consider virtualizing the list or paginating. Reflowing masonry with huge counts is expensive, and any JavaScript-based masonry library re-measures every item.

Accessibility and performance checklist

  • Keep DOM order logical: sequence, tab order and reading order must make sense when the layout is turned off.
  • Give each image a meaningful alt text, or alt="" for purely decorative ones, and give <img> explicit width and height so layout does not jump as pictures load (see Responsive Images).
  • Lazy-load images below the fold with loading="lazy".
  • Make clickable tiles real links or buttons, with a visible :focus-visible outline.
  • Respect prefers-reduced-motion for any hover zoom or entrance animation.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a CSS columns masonry, in which order do the items appear visually?

    Multi-column layout fills each column completely before starting the next, so the visual order runs down each column.
  2. 2. Which declaration stops a masonry tile from being split between two columns?

    break-inside: avoid keeps the tile in one piece. Without it a tall tile can break across columns.
  3. 3. What is a drawback of grid-auto-flow: dense?

    dense backfills earlier gaps with later items, so the visual order no longer matches the DOM order.
  4. 4. How should you treat native masonry (grid-lanes or masonry tracks) today?

    The feature is still being standardized and has uneven support, so build a reliable layout first and enhance where tested.
  5. 5. In the justified rows recipe, what does the ::after with a huge flex-grow do?

    A very large flex-grow on an empty pseudo-element takes nearly all leftover space on the last row, keeping the tiles at their natural size.

Summary

  • Pick a gallery technique by what matters: consistency (uniform grid), full pictures on even rows (justified flex), tight packing (columns masonry) or designed tiles (spanning grid).
  • Columns masonry is simple and robust, but orders items top to bottom per column; use break-inside: avoid.
  • Spanning grids with grid-row: span and dense flow need known shapes and can reorder items visually.
  • Native masonry (grid-lanes and related ideas) is experimental: use it only as a tested enhancement.
  • Keep DOM order meaningful, give images dimensions and alt text, and lazy-load below the fold.

Next lesson: Flexbox vs Grid: Choosing a Layout, where you learn how to choose between the two layout systems.