How to Make CSS Flexbox Horizontally Scrollable?

To enable flex items within a flexbox to remain on the same line and display a horizontal scrollbar when needed, you need to apply the following two essential CSS properties to the flex items (i.e. the children of the flexbox):

  1. flex-basis — to allow you to define the initial space each flex item should occupy within the flex container;
  2. flex-shrink: 0 — to prevent flex items from shrinking-to-fit when they become larger than the available space in the flex container.

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>

First, you need to ensure that the parent element is set as a flexbox and has overflow-x: auto set to allow horizontal scrolling when flex items overflow, for example, like so:

#parent {
  display: flex;
  height: 90px;
  justify-content: space-between;
  overflow-x: auto;

Please note that the flexbox container element needs to have "flex-wrap: nowrap" style rule applied as well. However, since nowrap is the default value of the flex-wrap property, it can be omitted.

Next, you need to add the flex-basis and flex-shrink: 0 properties to the flex items:

.child {
  flex-basis: 50%;
  flex-shrink: 0;
  height: 100%;
  background-color: aqua;

With these styles applied, each flex item will initially occupy 50% of the available space before any remaining space is distributed. By setting flex-shrink: 0, the flex items will not shrink if they surpass the available space, effectively forcing the flexbox to allow overflow, producing a result like the following:

Box #1
Box #2
Box #3

This post was published (and was last revised ) 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.