DEV Community

Cover image for Build a Before/After Slider With One Range Input and clip-path (React + Tailwind) | DeliverWebsite UI
Pooja Deliver Website
Pooja Deliver Website

Posted on

Build a Before/After Slider With One Range Input and clip-path (React + Tailwind) | DeliverWebsite UI

A before/after slider is the most convincing thing you can put on a redesign page. The visitor drags a
divider and compares the old site with the new one themselves. It looks like it needs a drag library. It
doesn't: one <input type="range"> and one clip-path do the whole job.

The whole component

import { useState, type ReactNode } from "react";

export function BeforeAfter({
  before,
  after,
}: {
  before: ReactNode;
  after: ReactNode;
}) {
  const [split, setSplit] = useState(50);

  return (
    <div className="relative overflow-hidden rounded-xl">
      <div>{after}</div>
      <div
        className="absolute inset-0"
        style={{ clipPath: `inset(0 ${100 - split}% 0 0)` }}
      >
        {before}
      </div>
      <div
        className="pointer-events-none absolute inset-y-0 w-px bg-blue-600"
        style={{ left: `${split}%` }}
      />
      <input
        type="range"
        min={0}
        max={100}
        value={split}
        onChange={(event) => setSplit(Number(event.target.value))}
        aria-label="Compare before and after"
        className="absolute inset-0 h-full w-full cursor-ew-resize opacity-0"
      />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Why it works

  • clip-path: inset(0 X% 0 0) cuts the "before" layer from the right. Changing one number moves the edge, and the browser never re-lays out the page.
  • The range input covers the whole area at opacity: 0, so a click or drag anywhere moves the divider.
  • Keyboard and screen readers work for free. Tab to it, then use the arrow keys. The label tells screen reader users what it compares.
  • The divider line is just a 1px div that follows the same percentage.

Make it feel finished

  • Start at 50 so both sides show on load.
  • Add a round handle on the line with an arrow icon, so people know it moves.
  • Label the corners "Before" and "After".
  • On touch screens, keep the input full-height so a thumb can grab it anywhere.

The full version, with a 1999-style "under construction" page on one side and a modern hero on the other, is
free on DeliverWebsite UI: https://ui.deliverwebsite.com/components/interactive-sections/before-after/

What would you compare with it: an old site, a design system update, or a dark/light theme?


More from me: Instagram · X · YouTube · Medium · Substack · Reddit · Pinterest · Free UI library

Top comments (0)