January 16, 2021

Native horizontal scrolling

I really like overflow-x: scroll and I think it is very much underused in favour for Javascript solutions when it comes to sliders on the web.

I, too, used to default to Javascript solutions until I realised they created more issues in some cases (I also got one-too-many last-minute requests from agency clients to change the mobile behaviour of a section to a slider).

Rely on the browser

I am proudly lazy and overflow-x: scroll just works in browsers. Using the horizontal scrollbar to scroll? Works. Scrolling on a touch screen? Works. Scrolling with your keyboard's arrow keys? Works. Your mouse's scroll wheel supports horizontal scrolling? That works too.

No tech debt. No JS dependencies. It just works!

iOS support

It's been a while since I tested this on a real iOS device, but last I checked it didn't work well without the -webkit-overflow-scrolling property:

.scroll-x {
  overflow-x: scroll;
}

@supports (-webkit-overflow-scrolling: touch) {
  .scroll-x {
    -webkit-overflow-scrolling: touch;
  }
}

Progressive enhancement

Using overflow-x: scroll does not mean you have to "settle" for a scrollbar if you don't want one. Glider.js is a good example of how you can progressively enhance a horizontal scrolling component with Javascript.

I also built a demo slider with Alpine.js

See the Pen Alpine.js slider with native scroll by Hussein Al Hammad (@hus_hmd) on CodePen.

Accessibility, UX and content discoverability

If you have multiple slides each of which contains some focusable elements (e.g. links), navigating a horizontal scrolling component with a keyboard gets you no surprises; the browser scrolls the in-focus element into view (within the component).

Another reason to love overflow-x: scroll is how it keeps content discoverability within a page possible when using the browser's built-in find functionality. Here is an example from the CSS-Tricks home page:

And here is another one from a Glider.js demo:

Wait, it gets better

CSS now allows you to customise the scrolling experience within a scrolling element with Scroll Snap. Ahmad Shadeed wrote a great article on Scroll Snap if you want to dive deep into this.