DEV Community

Cover image for Image Comparison Slider in CSS with 1 line of JS Code
Prahalad S
Prahalad S

Posted on • Updated on

Image Comparison Slider in CSS with 1 line of JS Code

Image Comparison Slider in CSS with 1 line of JS Code

Image description

Lets create input range slider and and two divs below it with class names .front, .back inside parent div with class name '.img-before-after'. Assign inline style width:50% to .front div

<div class="img-before-after">
    <input type="range" class="range" value="50">
    <div class="front" style="width: 50%;"></div>
    <div class="back"></div>
</div>
Enter fullscreen mode Exit fullscreen mode

Create CSS for img-before-after, input-range, input-slider-thumb, front, back

body {
    background: #d6d6d6;
}

.img-before-after {
    position: relative;
    width: 900px;
    height: 600px;
}

input[type="range"] {
    background: transparent;
    width: 100%;
    height: 100%;
    margin: 0;
    outline: none;
    position: absolute;
    z-index: 2;
    -webkit-appearance: none;
}

input[type="range"]::-webkit-slider-thumb {
    width: 10px;
    height: 600px;
    cursor: pointer;
    -webkit-appearance: none;
    background: black;
}
Enter fullscreen mode Exit fullscreen mode

Add background image for both .front and .back divs.

.front, .back {
    position: absolute;
    width: 100%;
    height: 600px;
    background: url("https://shorturl.at/kbKhz") no-repeat;
    background-size: cover;
    z-index: 1;
}
Enter fullscreen mode Exit fullscreen mode

Lets send .back div behind .front div with z-index and make it grayscale.

.back {
    filter: grayscale(1);
    z-index: 0;
}
Enter fullscreen mode Exit fullscreen mode

We need to increase/decrease the width of '.front' div dynamically when we drag the input slider. We have to append the input range value to width of '.front' div.

oninput="this.nextElementSibling.style.width = `${this.value}%`"
Enter fullscreen mode Exit fullscreen mode
<div class="img-before-after">
   <input type="range" class="range" value="50"
       oninput="this.nextElementSibling.style.width = `${this.value}%`">
   <div class="front" style="width: 50%;"></div>
   <div class="back"></div>
</div>
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Below you can watch how the width is increasing and decreasing in dev tools when we drag the slider range.

Image description

You can try with different variations in CSS like blur, invert etc like below.

blur

.back {
    filter: blur(5px);
    z-index: 0;
}
Enter fullscreen mode Exit fullscreen mode

Image description

invert

.back {
    filter: invert(1);
    z-index: 0;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Final Output: with grayscale

Image description

Thank you for watching...

Top comments (0)