Skip to main content
April 1, 2026Dan Rodney/6 min read

Grid: A Responsive Image Gallery (Masonry Layout)

Master CSS Grid for Modern Responsive Gallery Layouts

Why CSS Grid for Image Galleries

JavaScript-Free Masonry

CSS Grid eliminates the need for JavaScript libraries like Masonry.js, providing native browser support for complex layouts.

True Responsive Design

Auto-fitting columns that adapt to screen size without media query breakpoints for every device width.

Performance Benefits

Native CSS implementation reduces page load times and eliminates external library dependencies.

Topics Covered in This Web Development Tutorial:

Creating responsive grid layouts and implementing masonry-style galleries using modern CSS Grid techniques

Tutorial Learning Objectives

0/4

Exercise Preview

preview image gallery

Exercise Overview

In this exercise, you'll build a sophisticated image gallery that adapts flawlessly to any screen size while maintaining visual hierarchy through strategic element sizing.

Creating layouts with uniform elements is straightforward—the real challenge comes when you need different-sized items to work harmoniously together. For years, achieving Pinterest-style masonry layouts required complex JavaScript solutions. CSS Grid has fundamentally changed this landscape, becoming the first native CSS technology capable of delivering these advanced layouts with elegant simplicity.

The term "masonry layout" originates from David DeSandro's groundbreaking JavaScript library of the same name, released over a decade ago. While his library solved a critical need in the pre-Grid era, CSS Grid now offers native browser support for these patterns with superior performance and maintainability. Understanding both the historical context and modern implementation gives you a complete toolkit for responsive gallery design.

CSS Grid vs JavaScript Solutions

Historically, creating masonry layouts required JavaScript libraries like David DeSandro's popular Masonry library. CSS Grid is the first CSS technology that can achieve these complex layouts natively, improving performance and reducing dependencies.

Getting Started

Let's establish our development environment and examine the base structure we'll be working with.

  1. In your code editor, close any open files to start with a clean workspace.
  2. Navigate to the Grid Image Gallery folder located in Desktop > Class Files > yourname-Flexbox Grid Class. If you're using Visual Studio Code or a similar editor, open the entire folder to enable better file navigation and IntelliSense.
  3. Open index.html from the Grid Image Gallery folder.

    • Examine the structure—note the .gallery div container that holds our image collection. This semantic approach ensures accessibility and provides a clear CSS targeting strategy.
  4. Preview index.html in Firefox (or your preferred modern browser).

    • Scroll through the current layout to understand our starting point—images stacked vertically without any grid structure.
    • We'll transform this into a dynamic, responsive grid system.
  5. Keep index.html open in your browser for live preview as you work. This iterative development approach allows you to see the immediate impact of each change.

Project Setup Process

1

Close existing files

Clear your workspace in your code editor

2

Navigate to Grid Image Gallery folder

Located in Desktop > Class Files > yourname-Flexbox Grid Class

3

Open project files

Open index.html and preview in Firefox browser

4

Keep browser open

Maintain Firefox preview for live reload testing

Setting up the Grid for Small Screens

We'll start with a mobile-first approach, establishing a solid foundation for smaller screens before enhancing for larger displays.

  1. Switch back to your code editor.
  2. Open main.css from the css folder within the Grid Image Gallery directory.
  3. Below the body rule, add the following CSS Grid foundation:

    .gallery {
       display: grid;
       gap: 15px;
       grid-template-columns: 1fr;
    }
  4. Save the file and refresh the page in your browser.

    • You now have a single-column layout with consistent spacing between images—perfect for mobile devices.
    • Test the responsiveness by resizing your browser window. Notice how the layout remains clean on narrow screens but could benefit from multiple columns on wider displays.
    • The grid creates gaps between images, but the edges lack consistent spacing. Let's address this visual inconsistency.
  5. Return to your code editor to refine the layout.
  6. Enhance the .gallery rule with proper edge spacing:

    .gallery {
       display: grid;
       gap: 15px;
       padding: 15px;
       grid-template-columns: 1fr;
    }
  7. Save and refresh to see the improvement.

    • The gallery now has balanced spacing both between images and around the container edges, creating a more professional appearance.
Mobile-First Approach

Starting with a single column layout for mobile screens ensures optimal performance and user experience on smaller devices before adding complexity for larger screens.

Grid Properties Applied

display: grid
100
gap: 15px
75
padding: 15px
75
grid-template-columns: 1fr
90

Adjusting the Grid for Larger Screens

Now we'll implement responsive design principles to optimize the layout for larger screens, taking advantage of available horizontal space.

  1. Continue working in your code editor.
  2. Below the .gallery rule, add this responsive media query:

    @media (min-width: 600px) {
       .gallery {
          grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
       }
    }
  3. Save and test the responsive behavior in your browser.

    • Drag your browser window from narrow to wide and observe the dynamic column adjustment.
    • The auto-fill and minmax() functions work together to create an intelligent grid that adds columns as space allows, maintaining a minimum width of 250px per column.
    • On larger screens, we can enhance the visual breathing room with increased spacing.
  4. Return to your CSS for the final spacing adjustments.
  5. Expand the media query to include enhanced spacing for larger screens:

    @media (min-width: 600px) {
       .gallery {
          gap: 25px;
          padding: 25px;
          grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
       }
    }
  6. Save and test the progressive enhancement.

    • Notice how the spacing elegantly increases on wider screens, providing better visual hierarchy while maintaining the compact mobile layout where screen real estate is precious.
  7. Keep your code editor ready for the next enhancement phase.

repeat(auto-fill, minmax(250px, 1fr))
This powerful CSS Grid function automatically creates as many columns as will fit, with each column being at least 250px wide but able to grow to fill available space.

Small vs Large Screen Settings

FeatureSmall ScreensLarge Screens (600px+)
Gap Size15px25px
Padding15px25px
Columns1fr (single)auto-fill minmax(250px, 1fr)
Min Column WidthFull width250px
Recommended: Larger screens benefit from increased spacing and flexible column counts

Enlarging Some Photos

This is where CSS Grid truly shines—we'll create visual hierarchy by making certain images span multiple grid cells, achieving the coveted masonry effect.

  1. Switch to your code editor and open index.html.
  2. Examine the markup and locate images with the big class—these are strategically chosen photos that will become focal points in our layout.
  3. Switch back to main.css to implement the spanning behavior.
  4. Add this new rule below the existing .gallery rule:

    .big {
       grid-column: span 2;
       grid-row: span 2;
    }
  5. Save and refresh to see the transformation.

    • Selected photos now span multiple grid cells, creating visual interest and hierarchy. However, you may notice gaps appearing at certain screen sizes—this is normal behavior when items of different sizes compete for grid space.
    • CSS Grid provides an elegant solution for these spacing challenges.
  6. Return to your CSS to implement gap-filling logic.
  7. Enhance the media query with dense packing:

    @media (min-width: 600px) {
       .gallery {
          gap: 25px;
          padding: 25px;
          grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
          grid-auto-flow: dense;
       }
    }
  8. Save and test the improved layout.

    • The dense packing algorithm instructs the grid to backfill gaps with smaller items, creating a more cohesive visual experience.
    • Note that perfect bottom alignment isn't always achievable in masonry layouts—some gaps may persist at the container bottom depending on content and screen size. This is an inherent characteristic of responsive masonry systems, not a flaw in your implementation.
Grid Gaps Challenge

Adding spanning elements with grid-column: span 2 and grid-row: span 2 can create unwanted gaps in your layout at certain screen sizes. This is a common challenge in masonry layouts.

Grid Spanning Properties

grid-column: span 2

Makes an element span across 2 columns horizontally, creating wider featured images in the gallery layout.

grid-row: span 2

Makes an element span across 2 rows vertically, creating taller featured images for visual variety.

grid-auto-flow: dense

Fills in gaps by allowing items to be placed out of source order, creating a more compact layout.

Limiting the Width

Professional layouts require maximum width constraints to maintain readability and visual balance on ultra-wide screens.

  1. Add maximum width constraints to your media query:

    @media (min-width: 600px) {
       .gallery {

    Code Omitted To Save Space

    grid-auto-flow: dense;
          max-width: 1900px;
          margin: auto;
       }
    }
  2. Save and test on wide screens, or simulate by zooming out.

    • On ultra-wide displays, resize your browser to maximum width to see the 1900px constraint in action.
    • For smaller screens, simulate the effect by zooming out (hold Cmd/Ctrl and press Minus (-) repeatedly) until you can observe the width limitation behavior.
    • Reset your zoom to normal viewing by pressing Cmd/Ctrl + Zero (0).

Layout Constraints Applied

1,900px
Maximum width in pixels
600px
Breakpoint for larger screens
250px
Minimum column width
Masonry Layout Limitations

Remember that masonry layouts may not have perfectly aligned bottoms due to varying content heights. Some gaps at the bottom are normal when there aren't enough elements to perfectly fill the grid.

Key Takeaways

1CSS Grid eliminates the need for JavaScript libraries when creating masonry-style image galleries
2Use grid-template-columns with repeat(auto-fill, minmax()) for truly responsive column layouts
3Mobile-first approach with single columns scales better than desktop-first design
4Grid-auto-flow: dense property fills gaps created by spanning elements in masonry layouts
5Combining grid-column: span 2 and grid-row: span 2 creates featured elements in gallery layouts
6Media queries at 600px breakpoint provide optimal transition from mobile to desktop layouts
7Setting max-width and margin: auto prevents galleries from becoming too wide on large screens
8Masonry layouts inherently have bottom alignment limitations due to varying content heights

RELATED ARTICLES