"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Simple Image Comparison in CSS

Simple Image Comparison in CSS

Published on 2024-11-04
Browse:267

Simple trick for Image Comparison in CSS

Simple Image Comparison in CSS

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

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}%`"

Output:

Simple Image Comparison in CSS

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

Simple Image Comparison in CSS

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

blur

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

Simple Image Comparison in CSS

invert

.back {
    filter: invert(1);
    z-index: 0;
}

Simple Image Comparison in CSS

Final Output: with grayscale

Simple Image Comparison in CSS

Thank you for watching...

Release Statement This article is reproduced at: https://dev.to/prahalad/simple-image-comparison-in-css-48fd?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3