How to Create a Before/After Image Comparison Slider in CSS & JavaScript
A before/after image comparison slider is constructed by superimposing two identical-dimension images within a relative container. The bottom image displays the "After" state, while the top image displays the "Before" state and is clipped using CSS clip-path: inset(0 calc(100% - var(--position)) 0 0) or an animated width container with overflow: hidden. A draggable vertical handle tracks mouse or touch X-coordinates to update --position in real time.
Step 1: Dual-Layer Architecture with CSS Absolute Positioning
Structure your markup with two image elements inside a container. Make sure both images have identical aspect ratios and widths. Pin the modified "After" image as the background, and layer the "Before" image on top.
<div class="comparison-container" style="--slider-pos: 50%;">
<!-- After image underneath -->
<img src="edited-photo.jpg" alt="After retouching" class="img-after">
<!-- Before image on top with clipping -->
<div class="before-wrapper">
<img src="original-photo.jpg" alt="Original photo" class="img-before">
</div>
<!-- Draggable handle -->
<div class="slider-handle"></div>
</div>
Step 2: Precision Clipping via CSS clip-path or Container Width
You can clip the top layer using either width: var(--slider-pos) with overflow: hidden, or modern clip-path: inset(0 calc(100% - var(--slider-pos)) 0 0). Clip-path preserves image layout without reflowing internal assets.
.comparison-container {
position: relative;
overflow: hidden;
user-select: none;
}
.img-after {
display: block;
width: 100%;
height: auto;
}
.before-wrapper {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
/* Clip from right edge using CSS custom property */
clip-path: inset(0 calc(100% - var(--slider-pos)) 0 0);
}
Step 3: Interactive Pointer Tracking & Dragging Logic
Listen for pointerdown, pointermove, and pointerup events. Calculate the relative horizontal percentage between 0% and 100% and update the CSS custom property dynamically.
const container = document.querySelector('.comparison-container');
let isDragging = false;
function updatePosition(clientX) {
const rect = container.getBoundingClientRect();
const x = Math.max(0, Math.min(clientX - rect.left, rect.width));
const percent = (x / rect.width) * 100;
container.style.setProperty('--slider-pos', `${percent}%`);
}
container.addEventListener('pointerdown', (e) => { isDragging = true; updatePosition(e.clientX); });
window.addEventListener('pointerup', () => { isDragging = false; });
window.addEventListener('pointermove', (e) => {
if (isDragging) updatePosition(e.clientX);
});
Step 4: Zero-JS Accessible Fallback with Native
For a 100% keyboard-accessible and progressive enhancement implementation, place a transparent HTML <input type="range" min="0" max="100"> over the slider handle. This enables native keyboard arrow key adjustments and screen reader accessibility.
<input type="range" min="0" max="100" value="50" class="accessible-range-input"
aria-label="Image comparison slider"
oninput="this.parentElement.style.setProperty('--slider-pos', this.value + '%')">
<style>
.accessible-range-input {
position: absolute;
inset: 0;
opacity: 0;
cursor: ew-resize;
z-index: 10;
}
</style>
Next-Level Addons: Elevating Your Implementation
Take this technique further by combining it with complementary design token studios and animation tools:
A trick I use in almost every project: don't fight specificity battles with !important. Leverage modern CSS cascade layers (@layer) and CSS variables as design tokens—it makes dark/light theme switching and responsive tuning effortless.
Frequently Asked Questions
Practical answers to common implementation questions, browser quirks, and performance tips.
What is the advantage of using CSS clip-path over width: 50% for image comparison sliders?
Using `clip-path: inset()` allows the top image to remain at full 100% width while only visually revealing a portion. Using `width: 50%` requires wrapping the image in an extra `overflow: hidden` container and locking the inner image to the full container width so it doesn't squish.
Can a before/after slider work vertically instead of horizontally?
Yes! For vertical orientation, track clientY coordinates and adjust the top or bottom inset: `clip-path: inset(0 0 calc(100% - var(--slider-pos)) 0)`. The handle is rotated 90 degrees with a vertical `ns-resize` cursor.
How do I prevent image ghosting and dragging bugs on desktop browsers?
Add `user-select: none;` and `-webkit-user-drag: none;` to both image elements in CSS. Also, call `e.preventDefault()` on pointerdown to ensure the browser doesn't attempt to drag the image file to the desktop.
How do I make the comparison slider accessible to keyboard-only users?
Overlay an accessible HTML `` directly over the slider. Keyboard users can focus the slider using the Tab key and adjust the split percentage using Left/Right arrow keys.
What happens if the two comparison images have different aspect ratios?
If the aspect ratios differ, the images will misalign or shift when the slider passes over them. Always crop or export both "Before" and "After" images to the exact same pixel dimensions.