Skip to main content
Bojan Gvozderac
Download CV

Please note that my resume in its current form has been edited and stripped of a lot of experiences and projects to be easier to read and communicate better what experiences I find most valuable / relevant.

If you'd like to get to know me better and my career journey feel free to reach out on the contact page.

Carousel / Slider in 2 lines of CSS

Carousel / Slider in 2 lines of CSS

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


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

<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

I'm an experienced web and mobile developer specializing in JavaScript with over a decade and a half developing software I have proven that I have the knowledge and the expertise to deliver the goods!
If you'd like to get in touch and talk about potential projects, one of my articles, ask a question or just say "Hi!" please do by emailing bojan.gvozderac@monarch-software.com.