How to implement horizontal scrolling using Flexbox

ratracegrad

Jennifer Bland

Posted on July 20, 2019

How to implement horizontal scrolling using Flexbox

If you create websites, chances are you have been asked to create a horizontal scrolling component. It is extremely easy to implement this using just a few lines of Flexbox. Let me show you how.

Project Layout

We need to create a container that will contain all the images that we want to scroll. Here is the code:

<div class="container"><img src="images/bhutan1.jpg" alt="Bhutan" />
<img src="images/bhutan2.jpg" alt="Bhutan" />
<img src="images/bhutan3.jpg" alt="Bhutan" />
<img src="images/bhutan4.jpg" alt="Bhutan" />
<img src="images/bhutan5.jpg" alt="Bhutan" />
<img src="images/bhutan6.jpg" alt="Bhutan" />
<img src="images/bhutan7.jpg" alt="Bhutan" /></div>
Enter fullscreen mode Exit fullscreen mode

Styling the Project

Next step is to add styling so that the container scrolls horizontally. To do this I make the container display as flexbox. In addition, I am setting the overflow-x value to auto. Here is the style:

 .container {
    display: flex;
    overflow-x: auto;
}
Enter fullscreen mode Exit fullscreen mode

This is what the horizontal scroll looks like:

That does provide our requirement of a horizontal scroll area. I am not satisfied with how it looks. There are three things I want to change:

  • Add white space between the images
  • Get rid of the horizontal scrollbar
  • Place the scroller in the middle of the screen

The images are touching. Let’s add some white space between them. Here is the CSS for this:

.container img {
    margin-right: 15px;
}
Enter fullscreen mode Exit fullscreen mode

Next, I want to get rid of the horizontal scrollbar which I can do with this code:

.container::-webkit-scrollbar {
    display: none;
}
Enter fullscreen mode Exit fullscreen mode

The last change that I want to do is to center the scrolling area in the center of the screen. By default, the height of the html is the height of the elements. I need to make the height to be 100% of the viewport. Flexbox provides a way to center items with the align-items setting. To use this functionality, I am going to convert the body to display as flexbox. Here is the code that I am going to add for the body:

body {
    display: flex;
    align-items: center;
    height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

With these changes, here is what our final horizontal scroll area looks like.

Conclusion

It is very easy to create a horizontal scroll area using flexbox. Thanks for reading.

Training Courses

I create training courses on my website CodePrep. I have training courses on Vue, Webpack, Flexbox, functional programming and more. Check it out here.

💖 💪 🙅 🚩
ratracegrad
Jennifer Bland

Posted on July 20, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related