Horizontal Scrolling using CSS Grid

Jennifer Bland
3 min readDec 19, 2022

In this previous article, I showed how to do horizontal scrolling using flexbox. I was recently asked how to do the same scrolling but using CSS Grid instead. This article shows you how to do horizontal scrolling using CSS Grid.

Setting up my project

This project will contain the following files:

It will also include one folder called images. Inside this folder will be five images. The images in the folder are:

Our basic website

The index.html file contains the code for our basic website. It will display our five images in a horizontal scroll.

Here are the contents of my index.html file:

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>CSS Grid Horizontal Scroll</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <img src="images/image1.jpg" alt="image1"> <img src="images/image2.jpg" alt="image2"> <img src="images/image3.jpg" alt="image3"> <img src="images/image4.jpg" alt="image4"> <img src="images/image5.jpg" alt="image5"> <!-- more images --> </div> </body> </html>

Let’s walk through this code. In the head I have a link to my style.css file. I will cover this file later.

The body of the website contains a div with a.class of container.

Inside the div are five img elements that point to the five images located in the images folder.

That is it for our index.html file.

Adding horizontal scrolling of images

The secret sauce of making the images scroll horizontally is our CSS code.

Here is the code in the style.css file:

.container { display: grid; grid-auto-columns: calc(100% - 4rem); grid-auto-flow: column; grid-gap: 16px; overflow-x: auto; } .container img { width: 100%; height: auto; }

Let’s walk through this code.

display: grid; - This sets the container element to be a grid container, which means that its child elements will be placed onto a grid of rows and columns.

Jennifer Bland

Software Engineer. Google Developers Expert. Keynote Speaker. Entrepreneur. Mountain Climber. Neil Diamond fan. World traveler. jenniferbland.com & codeprep.io

Recommended from Medium