Before/After Image Card

Visually showcase a transformation with this interactive "before and after" image comparison slider.

This component is perfect for photographers, designers, and case studies. It allows users to drag a handle across an image to reveal the changes between an original and an updated version, providing a powerful way to demonstrate value and skill.

Screenshot of an interactive before/after image comparison slider.

Get Source Code Preview

About this Component

This is an interactive component powered by CSS and a small, dependency-free JavaScript snippet. The two images are layered on top of each other, and the script dynamically changes the clipping of the top image as the user drags the handle. It's also fully responsive and includes support for touch devices.

Features

Code Breakdown

HTML Structure

The card contains a main div with the class .ba-image-container. Inside, the two images ("before" and "after") are placed. This is followed by an empty div that will serve as the draggable handle. It's important that the "after" image comes second in the HTML, as it will be layered on top.

CSS Styling

The .ba-image-container is set to position: relative to act as the positioning context. The "after" image is then absolutely positioned to sit directly on top of the "before" image. The core of the visual effect is the clip-path property on the .ba-image-after class. By default, clip-path: polygon(0 0, 50% 0, 50% 100%, 0 100%) only reveals the left 50% of the image. The slider handle is another absolutely positioned div with pseudo-elements used to create the draggable circles.

JavaScript Logic

The script listens for mouse and touch events (mousedown, mousemove, touchstart, etc.) on the image container. When a drag action starts, it calculates the cursor's horizontal position as a percentage relative to the container's width. It then dynamically updates the inline style of the "after" image, changing the clip-path percentage to match the cursor's position. It also updates the left property of the handle to keep it aligned with the clipping edge.

Code

Here is the complete, self-contained code. To use it, simply replace the src attributes of the two elements with your own "before" and "after" images.

View Output