EL

Eljan Simuratli

1/31/2025

Build a Slider with Just 2 Lines of CSS - Scroll Snap Magic!

1 Mins Read
Build a Slider with Just 2 Lines of CSS - Scroll Snap Magic!

Today’s topic is creating a simple slider with just a few lines of CSS.
To achieve this, we’ll explore the CSS Scroll Snap feature.
CSS Scroll Snap makes building carousels or step-by-step content sliders easy by aligning scrollable content at specific points.

Let’s take a look at the code. We’ll create a slider with 3 items: 1, 2, and 3.

First, let’s create the basic slider items:

<div class="container">
  <section class="child child1">1</section>
  <section class="child child2">2</section>
  <section class="child child3">3</section>
</div>
.container {
   display: flex;
   overflow-x: scroll;
}

.child {
  scroll-snap-align: start;
  display:grid;
  place-content:center;
  font-size:30px;
  color:white;
  font-weight:bold;
}

.child1{
  background:red;
}

.child2{
  background:orange;
}


.child3{
  background:yellow;
}

It will look like this.

sl

Now let’s make min-width and height 100%.

.child {
  min-width: 100vw;
  height:100vh;
}
sl

The Main part of making it a slider:

.container {
   scroll-snap-type: x mandatory; 
}

.child {
  scroll-snap-align: start;
}

If we use this it will work like a slider:

sldier

You can check from there: CodePen