How to Make CSS Grid Layout Horizontally Scrollable?

To enable grid items within a grid layout to remain on the same line and display a horizontal scrollbar when needed, you need to apply the following three essential CSS properties to the grid container:

  1. grid-auto-columns — to allow you to define the initial width each grid item should occupy within the grid container;
  2. grid-auto-flow: column — to arrange grid items in columns when there is available space;
  3. overflow-x: auto — to allow horizontal scrolling when the content exceeds the grid container's width.

By using the grid-auto-flow: column, grid-auto-columns, and overflow-x: auto properties together, you can create a grid layout where grid items are automatically placed in columns with a specified width, allowing you to achieve a horizontal scrolling effect when the content exceeds the container's width.

For example, let's suppose you have the following HTML:

<div id="parent">
  <div>Box #1</div>
  <div>Box #2</div>
  <div>Box #3</div>
</div>

By setting grid-auto-flow: column, grid-auto-columns: 50%, and overflow-x: auto, the grid layout will arrange the items in columns, each taking up 50% of the available width, and provide horizontal scrolling when necessary:

#parent {
  display: grid;
  height: 90px;
  grid-gap: 0 20px; /* row gap: 0, column gap: 20px */
  grid-auto-flow: column; /* place grid items in columns */
  grid-auto-columns: 50%; /* default size for the columns in the grid */
  overflow-x: auto;
}

The will produce an output like the following:

Box #1
Box #2
Box #3

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.