Skip to content
← Back to quick wins
Quick Win

Carousel / Slider in 2 lines of CSS

Instead of writing a bunch of JS just to slide some images around write these 2 lines of CSS and you're golden!

Tags
#css
Carousel / Slider in 2 lines of CSS featured image

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 it

Slide 01

Slide 01

Snap-to-panel scrolling

Slide 02

Slide 02

Pure CSS, no JS carousel logic

Slide 03

Slide 03

Built to show the scroll-snap pattern


In 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

1<div class="parent">
2 <div class="child-1" />
3 <div class="child-2" />
4 <div class="child-3" />
5</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 🤠

1.parent {
2 display: flex;
3
4 width: 580px;
5 height: 420px;
6
7 margin: 0 auto;
8
9 overflow-x: auto;
10 overflow-y: hidden;
11
12 scroll-snap-type: x mandatory;
13 }
14 .parent > div {
15 flex: 0 0 100%;
16
17 scroll-snap-align: start;
18
19 background-position: center;
20 background-size: cover;
21
22 }
23 .child-1 {
24 background-image: url("path_to_slide_1_background");
25 }
26 .child-2 {
27 background-image: url("path_to_slide_2_background");
28 }
29 .child-3 {
30 background-image: url("path_to_slide_3_background");
31 }

Can you spot the 2 "magic" CSS lines? It's these 2

1scroll-snap-type: x mandatory;

and

1scroll-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