Horizontal slider is one of the most used sliders in design because of its simplicity and ease. Personally, while learning html and css I wish I could do somethings with those two and not having to write some javascript and also in a very simple and fast way.
I have seen a lot of approaches to this particular problem using css and I believe it might still be kind of hard for some upcoming developers. I came about going about this problem in a very simple way.
The first step is to create a container that contain all the slides;
<body>
<div class="super-container">
<div class="wrapper">
<div class="slide" ></div>
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
</div>
</div>
</body>
After that is the styling which is the major thing that is required to achieve what we want to achieve.
In this tutorial, we will use the css property white-space:nowrap to make the slides be on a horizontal line , side by side and the overflow:scroll property scroll will be responsible to make it scroll.
.wrapper{
width:100%;
height: auto;
padding-top:20px;
overflow-y: hidden;
overflow-x: scroll;
white-space: nowrap;
}
Notice from the code above that the wrapper containing the slides was given the property white-space:nowrap. White-space property talks about how a white space is handled in our wrapper div. The value nowrap read as no-wrap makes it that the divs will never wrap to the next line.
So the next thing we need to do is to style the slides to look the way we want it. Some wants 3 items to show before the next one while some wants it to show one after the other.
In this tutorial, it will show one after the other and with a side hint of the next slide showing. Below is the code.
.slide{
height:120px;
width:80%;
display: inline-block;
background-image: url("https://www.refrigeratedfrozenfood.com/ext/resources/NEW_RD_Website/DefaultImages/default-pasta.jpg?1430942591");
background-size: cover;
border-radius:10px;
margin-left:15px;
}
The most important css property from the code above is display: inline-block which is very important in what we are trying to build. It makes the div stay side by side, it doesnβt add a line break as long as the divs still have space to stay side by side.
With just these few codes, we have created a horizontal slider. Personally, I believe this is the simplest way to go about it.
Check the live code on codepen and also see the live result;
https://codepen.io/grace_2241/pen/YzGKjBw
And you can also check the video on my youtube channel and subscribe.
Top comments (1)
Amazing piece!