Image Comparison Slider in CSS with 1 line of JS Code
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>
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;
}
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;
}
Lets send .back
div behind .front
div with z-index
and make it grayscale.
.back {
filter: grayscale(1);
z-index: 0;
}
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}%`"
<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>
Output:
Below you can watch how the width is increasing and decreasing in dev tools when we drag the slider range.
You can try with different variations in CSS like blur, invert etc like below.
blur
.back {
filter: blur(5px);
z-index: 0;
}
invert
.back {
filter: invert(1);
z-index: 0;
}
Final Output: with grayscale
Thank you for watching...
Top comments (0)