Very often you’ll find yourself needing to create some kind of slider / carousel components and usually what you’ll do is reach for a library or start hacking away on some JavaScript code to make that happen but modern CSS is insanely powerful and with just 2 lines you can, depending on your needs, get it completely done or in the worst case it’ll get you very near where you want to be.
Here’s a horizontal image slider component that I built in 2 mins, go ahead play around with itIn this case we’re sliding some images around but you can make anything slide, some cards around for example.
Now lets take a look at the code and those 2 magic lines of CSS!
This is our HTML
<div class="parent">
<div class="child-1" />
<div class="child-2" />
<div class="child-3" />
</div>
and now the CSS, we have a bit of fluff CSS to display the above slider the way it is but no worries I’ll highlight the 2 special lines 🤠
.parent {
display: flex;
width: 580px;
height: 420px;
margin: 0 auto;
overflow-x: auto;
overflow-y: hidden;
scroll-snap-type: x mandatory;
}
.parent > div {
flex: 0 0 100%;
scroll-snap-align: start;
background-position: center;
background-size: cover;
}
.child-1 {
background-image: url("path_to_slide_1_background");
}
.child-2 {
background-image: url("path_to_slide_2_background");
}
.child-3 {
background-image: url("path_to_slide_3_background");
}
Can you spot the 2 “magic” CSS lines? It’s these 2
scroll-snap-type: x mandatory;
and
scroll-snap-align: start;
That’s basically all it takes!
The first line tells the browser we want scroll snapping to be mandatory on the X axis
and the second line tells the browser how we want the scroll to align.
Of course this can be configured and you can check out how and what in the docs for scroll snap type
and scroll snap align