How to create horizontally scrollable sections with Flexbox
This article is example focused, and the problem we’ll be solving is pretty standard.
The road to learning by precept is long, by example short and effective — Lucius Seneca
This article is example focused, and the problem we’ll be solving is pretty standard.
How do you create a section that scrolls horizontally — with great support on browsers, mobile inclusive?
Flexbox! Yeah, that’s the short answer.
Let’s flesh that out a bit.
Basic Code Setup
Consider the markup below.
It’s essentially a section
with a couple div
elements as children.
Code Styles
Because no one loves ugly designs, let’s have some very basic styling:
The first few lines, 1 -5 explicitly sets the width and height of the root elements to 100%
Line 8 gives the body a background-color, line 9 takes away margin around the body
, while lines 10 to 12 ensures that the direct child element of body
is positioned exactly at the center — vertically and horizontally.
To see this in effect, give the child element, <section class=”card">
some styling:
Line 2 is quite obvious. Line 3 ensures that the section takes 100%
of it’s container’s width by default. Line 4 makes sure that the height of the section never goes below 200px
Now everything should look like this at this point:
Now we will put the card--content
“divs ” within the card
section to good use.
Let’s have some very simple styles again.
First off, make card
a flex-container:
.card {display: flex}
Then style .card--content
as follows:
Line 3 ensures that the width of each card is never less than 200px
, everything else is pretty simple.
Here’s the result of that:
As you may have noticed, the entire page scrolls. This is because there are more elements than can be fit into the card
section.
Let’s specifically tell the browser to only scroll the card
section.
To do that, add this:
.card {
overflow-x: auto;
}
And we have a scrollable section:
Good!
Hiding the Scrollbar
For UX reasons you may want to hide the scrollbar, and still have a scrollable section.
There’s an easy way out — for webkit browsers at least.
.card::-webkit-scrollbar {
display: none;
}
This will hide the scrollbars, which is arguably more beautiful.
Applications
I have used empty boxes to illustrate the point here. However, there could be a lot of application for this simple technique — a technique very valuable in mobile apps where you don’t have a lot of viewing space
Here are a couple examples:
(i) You could have a bunch of Images in a horizontal section — your version of instangram
(ii) You could have just a bunch of texts, if that’s useful for you.
To be honest, the possibilities are endless — all at your service.
Want to become Pro?
Download my free CSS Grid cheat sheet, and also get two quality interactive Flexbox courses for free!