Image Comparison Slider - Basic
Compare two images, one over the other, by panning a slider bar back and forth.
Demo
HTML
<!-- The important part here is the `.container`, two children with an image, and the `range` element -->
<div class="container">
<div id="left">
<img src="https://images.unsplash.com/photo-1763236390948-fcc866ddb17a?crop=entropy&cs=srgb&fm=jpg&ixid=M3wzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE3Njk3MTQ1MjB8&ixlib=rb-4.1.0&q=85&w=800"
width="800"
height="533"
alt="Sample image, rugged sunlit cliffsides with bright blue sky above" />
</div>
<div id="right">
<img src="https://images.unsplash.com/photo-1768029536371-977c7d50b5e4?crop=entropy&cs=srgb&fm=jpg&ixid=M3wzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE3Njk3MTQ1MjB8&ixlib=rb-4.1.0&q=85&w=800"
width="800"
height="533"
alt="Sample image, rugged rock being battered by waves with pastel sky above" />
</div>
<input type="range">
</div>CSS
/* General layout */
.container {
position: relative;
max-width: 800px;
height: auto;
aspect-ratio: 6 / 4;
display: grid;
place-items: center;
overflow: hidden;
}
/* Overlap the image containers, and stretch the images to fill the container */
div div {
position: absolute;
height: 100%;
left: 0;
right: 0;
}
img {
height: 100%;
object-fit: cover;
}
div div {
position: absolute;
height: 100%;
left: 0;
right: 0;
}
#left img {
object-position: 0 0;
}
#right img {
object-position: 100% 0;
}
/* Setup the `range` element */
input {
--thumb-width: 17px;
width: calc(100% + var(--thumb-width));
z-index: 1;
}
/* Set the anchor position */
#right {
left: anchor(--thumb center);
}
/* Attach the slider handle to the anchor*/
input::-webkit-slider-thumb {
anchor-name: --thumb;
}
input::-moz-range-thumb {
anchor-name: --thumb;
}
input::-ms-thumb {
anchor-name: --thumb;
}JS
No JS required.Baseline
CodePen
See the Pen on CodePen.