HTML & CSS 3d ago 4 views 5 min read

How to create a responsive image gallery with CSS Grid

Build a fluid, responsive image grid that adapts to any screen size using modern CSS Grid properties. Follow these steps to create a layout that shifts from a single column on mobile to a complex mosaic on desktop.

Riya K.
Updated 1d ago
Sponsored

Cloud VPS — scale in minutes

Instantly deploy SSD cloud VPS with guaranteed resources, snapshots and per-hour billing. Pay only for what you use.

You will create a responsive image gallery that automatically adjusts its layout based on the viewer's screen width. These steps target modern browsers supporting CSS Grid Level 2 and standard HTML5 elements. You will define a grid template that shifts from a single column on mobile devices to a complex multi-column layout on desktop screens.

Prerequisites

  • A modern web browser that supports CSS Grid (Chrome, Firefox, Safari, Edge).
  • A code editor like VS Code, Sublime Text, or Notepad++.
  • Basic knowledge of HTML structure (divs, img tags).
  • A local development environment or a live web server to test the layout.
  • Access to a set of placeholder images (e.g., from Unsplash or Lorem Picsum).

Step 1: Create the HTML structure

Start by creating a new HTML file named index.html and add a main container div with the class "gallery". Inside this container, place eight image elements. Each image must have a unique ID and a src attribute pointing to a valid image URL.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Gallery</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="gallery">
        <img src="https://picsum.photos/400/600?random=1" alt="Image 1" id="img-1">
        <img src="https://picsum.photos/400/600?random=2" alt="Image 2" id="img-2">
        <img src="https://picsum.photos/400/600?random=3" alt="Image 3" id="img-3">
        <img src="https://picsum.photos/400/600?random=4" alt="Image 4" id="img-4">
        <img src="https://picsum.photos/400/600?random=5" alt="Image 5" id="img-5">
        <img src="https://picsum.photos/400/600?random=6" alt="Image 6" id="img-6">
        <img src="https://picsum.photos/400/600?random=7" alt="Image 7" id="img-7">
        <img src="https://picsum.photos/400/600?random=8" alt="Image 8" id="img-8">
    </div>
</body>
</html>

You will see eight images loaded from the Lorem Picsum service. The random parameter ensures each image displays a different picture. Save the file and open it in your browser to see the default unstyled layout.

Step 2: Initialize the CSS Grid container

Create a new file named style.css and select the .gallery class to apply grid properties. Set the display property to grid to activate the layout engine. Define the grid-template-columns using the minmax function to create flexible columns that grow and shrink between a minimum width of 200 pixels and a maximum of 1fr (one fraction of available space).

.gallery {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    padding: 20px;
    font-family: system-ui, -apple-system, sans-serif;
}

The auto-fit keyword tells the browser to add as many columns as possible without forcing a column narrower than 200 pixels. The gap property creates consistent spacing between images. This setup creates a responsive grid that automatically adjusts without media queries yet.

Step 3: Style the images

Apply styling to the image elements to ensure they fit perfectly within their grid cells. Set width to 100% and height to auto so images fill the column width while maintaining their aspect ratio. Add overflow hidden to the parent container and object-fit cover to the images to crop content uniformly if aspect ratios differ.

.gallery img {
    width: 100%;
    height: auto;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.gallery img:hover {
    transform: scale(1.05);
    box-shadow: 0 8px 12px rgba(0, 0, 0, 0.15);
}

These rules add a subtle hover effect that scales the image slightly and deepens the shadow. The border-radius creates rounded corners for a modern look. The transition property makes the hover effect smooth rather than instant.

Step 4: Add a specific column count for large screens

While auto-fit handles most cases, you can force a specific layout for very large screens if desired. Use a media query to target screens wider than 1200 pixels and set the grid to exactly four columns. This overrides the default auto-fit behavior to ensure a consistent wide layout on desktop monitors.

@media (min-width: 1200px) {
    .gallery {
        grid-template-columns: repeat(4, 1fr);
    }
}

This block ensures that on large monitors, the gallery displays four equal columns. It prevents the grid from creating too many narrow columns on ultra-wide displays. The 1fr unit distributes space equally among the four columns.

Step 5: Create a masonry-like layout with grid-auto-flow

Modify the grid flow to allow rows to fill from left to right rather than top to bottom. Set grid-auto-flow to dense to fill gaps in the grid with smaller items if they exist. This is useful if you mix images of different sizes, though our current setup uses uniform heights.

.gallery {
    grid-auto-flow: dense;
    grid-auto-rows: 200px;
}

Setting a fixed grid-auto-rows height ensures all images stretch to the same height. This creates a uniform grid rather than a masonry layout where heights vary. Dense flow ensures no empty gaps appear if you were to add images of varying sizes later.

Verify the installation

Open index.html in your browser and resize the window width. Observe how the number of columns changes automatically. At 800 pixels, you should see four columns. At 600 pixels, the grid should shift to three columns. At 400 pixels, it should shift to two columns. Below 400 pixels, it should display a single column.

Inspect the element using browser DevTools (F12). Check the computed styles for .gallery. Confirm that grid-template-columns contains the minmax value. Hover over an image to verify the transform and box-shadow changes occur smoothly.

Troubleshooting

If images overlap or break the layout, check the gap property value. A gap larger than the image width can cause visual issues on small screens. Ensure the viewport meta tag is present in the HTML head to prevent the browser from scaling the page incorrectly. If images do not stretch to fill the column, verify that width is set to 100% and height is set to auto. If the grid does not reflow at all, clear your browser cache and hard refresh (Ctrl+F5) to remove old CSS styles. Ensure you are using a browser that supports CSS Grid Level 2, as older browsers may ignore the display: grid property.

Sponsored

Linux Dedicated Server

Rock-solid Linux dedicated servers with root access, KVM-IPMI and fully managed options. CentOS, Ubuntu, Debian, Rocky and AlmaLinux.

Tags: CSSLayoutGridResponsiveFrontend
0
Was this helpful?

Related tutorials

Comments 0

Login to leave a comment.

No comments yet — be the first to share your thoughts.