← Blog8 min read#scroll area#scrollbar#react

Custom Scroll Area in React: Styled Scrollbar, Shadow Fade, Auto-Hide

Build a fully custom React scroll area with styled scrollbars, top/bottom shadow fades, and auto-hide behavior - no library required.

code editor screen showing React component scroll area code

Why the Default Scrollbar Is Killing Your UI

The browser's native scrollbar is about 17px wide on Windows Chrome and literally unstyled - it looks like it belongs in a Windows 95 file picker. On macOS it vanishes by default (overlay mode), but the moment someone plugs in a mouse, it reappears in all its gray, chunky glory. You're shipping beautiful components and then this thing shows up.

In practice, this matters most inside constrained UI elements: sidebars, chat windows, code panels, data grids. A 240px-wide sidebar with a 17px scrollbar loses more than 7% of its horizontal space to chrome that clashes with everything. That's not a minor aesthetic complaint - it actively breaks layouts.

The good news is CSS ::-webkit-scrollbar pseudo-elements and the newer scrollbar-width / scrollbar-color spec (supported in Firefox since 64, Chrome since 121) give you real control. Combine those with a thin React wrapper and you get a scroll area that feels like a deliberate design decision rather than a browser default.

Worth noting: pure CSS scrollbar styling has limits. You can't reliably hide the scrollbar until hover across all browsers, and you can't add shadow fades that indicate overflow without a component. That's why we're building a small wrapper - not pulling in a 40 KB library.

The Component Structure You Actually Want

Keep it simple: one outer container with overflow: hidden and position: relative, one inner scroller with overflow-y: auto, and two absolutely-positioned gradient overlays for the top and bottom fades. Four elements total. That's the whole thing.

// ScrollArea.tsx
import { useRef, useState, useEffect, useCallback } from 'react';

interface ScrollAreaProps {
  children: React.ReactNode;
  className?: string;
  maxHeight?: string;
  fadeSize?: number; // px
  hideDelay?: number; // ms
}

export function ScrollArea({
  children,
  className = '',
  maxHeight = '400px',
  fadeSize = 32,
  hideDelay = 1200,
}: ScrollAreaProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [showTop, setShowTop] = useState(false);
  const [showBottom, setShowBottom] = useState(false);
  const [scrollbarVisible, setScrollbarVisible] = useState(false);
  const hideTimer = useRef<ReturnType<typeof setTimeout>>();

  const checkScroll = useCallback(() => {
    const el = scrollRef.current;
    if (!el) return;
    setShowTop(el.scrollTop > 8);
    setShowBottom(el.scrollTop + el.clientHeight < el.scrollHeight - 8);
  }, []);

  const handleScroll = useCallback(() => {
    checkScroll();
    setScrollbarVisible(true);
    clearTimeout(hideTimer.current);
    hideTimer.current = setTimeout(() => setScrollbarVisible(false), hideDelay);
  }, [checkScroll, hideDelay]);

  useEffect(() => {
    checkScroll();
    return () => clearTimeout(hideTimer.current);
  }, [checkScroll]);

  return (
    <div
      className={`relative overflow-hidden ${className}`}
      style={{ maxHeight }}
    >
      {/* Top fade */}
      {showTop && (
        <div
          className="pointer-events-none absolute inset-x-0 top-0 z-10"
          style={{
            height: fadeSize,
            background: 'linear-gradient(to bottom, var(--scroll-fade-color, #fff), transparent)',
          }}
        />
      )}

      {/* Scrollable content */}
      <div
        ref={scrollRef}
        onScroll={handleScroll}
        className={`h-full overflow-y-auto scroll-area-inner ${
          scrollbarVisible ? 'scrollbar-visible' : 'scrollbar-hidden'
        }`}
        style={{ maxHeight }}
      >
        {children}
      </div>

      {/* Bottom fade */}
      {showBottom && (
        <div
          className="pointer-events-none absolute inset-x-0 bottom-0 z-10"
          style={{
            height: fadeSize,
            background: 'linear-gradient(to top, var(--scroll-fade-color, #fff), transparent)',
          }}
        />
      )}
    </div>
  );
}

The fadeSize prop defaults to 32px - enough to signal overflow without eating into content. You'll tweak this depending on font size and line height. For dense data tables, 24px feels right. For paragraph-heavy sidebars, bump it to 48px.

One more thing - the pointer-events-none on the fade overlays is non-negotiable. Skip it and you'll block click events on list items near the edges, which is an infuriating bug to track down at 11pm.

Styling the Scrollbar with CSS

Drop this in your global CSS or a CSS module. The ::-webkit-scrollbar approach covers Chrome/Edge/Safari. scrollbar-width and scrollbar-color cover Firefox. Together you've got 97%+ of browsers as of 2026.

/* globals.css  */
.scroll-area-inner {
  /* Firefox */
  scrollbar-width: thin;
  scrollbar-color: transparent transparent;
  transition: scrollbar-color 0.2s ease;
}

.scroll-area-inner.scrollbar-visible {
  scrollbar-color: rgba(0, 0, 0, 0.25) transparent;
}

/* Chromium */
.scroll-area-inner::-webkit-scrollbar {
  width: 6px;
}

.scroll-area-inner::-webkit-scrollbar-track {
  background: transparent;
}

.scroll-area-inner::-webkit-scrollbar-thumb {
  background: transparent;
  border-radius: 99px;
  transition: background 0.2s ease;
}

.scroll-area-inner.scrollbar-visible::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.25);
}

.scroll-area-inner.scrollbar-visible::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.45);
}

The 6px thumb width is a sweet spot - visible enough to grab, subtle enough not to dominate. Go below 4px and touch targets suffer. Go above 8px and you're back to looking like a native scrollbar.

Honestly, the transition from transparent to visible is what makes the auto-hide feel polished rather than janky. Without it the scrollbar just pops in and out, which is worse than no auto-hide at all. The 0.2s ease gives it that macOS-overlay feel even on Windows.

Quick aside: ::-webkit-scrollbar-thumb transitions don't work in all versions of Safari pre-2025. If that matters for your users, skip the transition on the thumb and just switch classes instantly. The opacity change is still smoother than the browser default.

Shadow Fade with CSS Custom Properties

Hardcoding #fff in the gradient kills the component in dark mode or on colored backgrounds. The --scroll-fade-color CSS variable lets consumers just set one property and move on. You're not managing theme logic inside the component - you're exposing a surface.

// Dark mode usage
<ScrollArea
  className="dark"
  style={{ '--scroll-fade-color': '#1a1a2e' } as React.CSSProperties}
  maxHeight="320px"
>
  {items.map(item => <ListItem key={item.id} {...item} />)}
</ScrollArea>

// Or set it globally in your theme
/* :root { --scroll-fade-color: #ffffff; }
   .dark { --scroll-fade-color: #0f0f13; } */

If you're using Tailwind's dark mode with class strategy, you can set the variable in your CSS layer and it just works. No JS needed. The component reads whatever the current color is through inheritance.

That said, there's a subtlety here: the fade only masks content cleanly if the background behind the scroll area matches --scroll-fade-color. If you've got a gradient or image background, you'll need a different approach - either mask-image with a linear gradient on the inner scroller, or accept that the fade won't be pixel-perfect.

/* Alternative: mask-image approach for gradient backgrounds */
.scroll-area-inner {
  -webkit-mask-image: linear-gradient(
    to bottom,
    transparent 0,
    black 32px,
    black calc(100% - 32px),
    transparent 100%
  );
  mask-image: linear-gradient(
    to bottom,
    transparent 0,
    black 32px,
    black calc(100% - 32px),
    transparent 100%
  );
}

The mask-image approach is cleaner for complex backgrounds but it always fades both ends simultaneously. You'd need ResizeObserver + scroll tracking to conditionally toggle the mask regions - which is exactly what the component's showTop/showBottom state already handles for the gradient overlay method. Pick whichever fits your context.

Auto-Hide Scrollbar Behavior

The auto-hide logic in the component above uses a setTimeout ref that resets on each scroll event. When scrolling stops, hideDelay milliseconds later the scrollbar-visible class gets removed and CSS transitions it back to transparent. Clean, no RAF loops, no intersection observers.

// If you want it to show on hover too (not just scroll)
// wrap the outer div with onMouseEnter/Leave:

<div
  className={`relative overflow-hidden ${className}`}
  style={{ maxHeight }}
  onMouseEnter={() => setScrollbarVisible(true)}
  onMouseLeave={() => {
    clearTimeout(hideTimer.current);
    hideTimer.current = setTimeout(() => setScrollbarVisible(false), 400);
  }}
>

Whether you want hover-to-show depends on your product. Chat windows and sidebars benefit from it - users expect to scroll without needing to start scrolling first. Code editors and infinite lists are fine with scroll-only reveal since the user's intent is already clear.

Look, there's also an accessibility angle here. The WCAG 2.2 success criterion 2.5.8 (Target Size) sets a minimum 24x24px target for interactive controls. If you hide the scrollbar entirely by default and rely on keyboard navigation, make sure you're not trapping focus inside the scroll area. Test with Tab and arrow keys.

One edge case worth handling: if the content fits entirely inside the container, showBottom stays false from the initial checkScroll call and no fades render. But the scrollbar CSS still applies - you'd see an invisible scrollbar track taking up 6px for no reason. Add a hasOverflow state and conditionally apply the CSS class if you care about pixel-perfect layout.

Composing It Into Real UI

Here's the component in a sidebar navigation context, which is probably the most common use case. The --scroll-fade-color matches the sidebar background and the max height is viewport-relative so it doesn't overflow the layout.

import { ScrollArea } from '@/components/ScrollArea';

export function Sidebar({ navItems }: { navItems: NavItem[] }) {
  return (
    <aside className="w-64 bg-[#0f0f13] border-r border-white/10">
      <div className="p-4">
        <Logo />
      </div>
      <ScrollArea
        maxHeight="calc(100vh - 80px)"
        fadeSize={40}
        hideDelay={1000}
        style={{ '--scroll-fade-color': '#0f0f13' } as React.CSSProperties}
      >
        <nav className="px-2 pb-4 space-y-1">
          {navItems.map(item => (
            <NavItem key={item.href} {...item} />
          ))}
        </nav>
      </ScrollArea>
    </aside>
  );
}

If you're building glassmorphism UIs - and if you've spent any time in the glassmorphism components section you probably are - you'll want to match the fade to the blurred panel color, not the page background. That usually means a semi-transparent dark or light value rather than a solid hex.

For glassmorphism generator outputs where the panel uses backdrop-filter: blur(12px), the fade trick doesn't work perfectly because there's no single background color to match. Use mask-image in that case and skip the scroll-fade overlays entirely.

That said, the Empire UI component library handles a lot of these scroll patterns inside pre-built components like modals, drawers, and command palettes. If you're rolling a design system from scratch, it's worth checking what's already there before you build yet another scroll area abstraction.

Performance and ResizeObserver

One thing people miss: if the content inside the scroll area changes height dynamically (lazy-loaded items, accordion toggles, async data), the showBottom state can get stale. You need a ResizeObserver on the inner scroller to re-run checkScroll when the content height changes.

useEffect(() => {
  const el = scrollRef.current;
  if (!el) return;

  const observer = new ResizeObserver(() => checkScroll());
  // Observe the inner content, not the scroll container
  if (el.firstElementChild) {
    observer.observe(el.firstElementChild);
  }

  return () => observer.disconnect();
}, [checkScroll]);

Observe the first child - the content - not the scroll container itself. The container has maxHeight set, so its size won't change when content grows. The content inside grows. Classic mistake.

On the performance side, ResizeObserver callbacks are batched per frame by browsers so you won't get thousands of calls per second. The checkScroll function itself is just reading three numeric properties off a DOM node - it's cheap. Don't wrap it in requestAnimationFrame unless you're seeing actual jank in profiling.

Scroll event handlers are different. Those can fire 60-120 times per second while scrolling. The component as written doesn't do heavy work in the scroll handler (just setState twice and a setTimeout reset), but if you're extending it with custom scroll-linked animations, throttle with requestAnimationFrame. The box shadow generator and similar tools in the library do exactly this for their preview panels.

FAQ

Can I use this scroll area with Radix UI or shadcn/ui?

Yes. Radix has its own ScrollArea primitive - this custom version is an alternative if you want more control over the fade and auto-hide without the Radix dependency. They don't conflict if you use both.

Why does the scrollbar styling not work in Firefox?

Firefox doesn't support ::-webkit-scrollbar pseudo-elements. Use scrollbar-width: thin and scrollbar-color instead - those are the standard properties and Firefox has supported them since version 64.

How do I make the fade work on a dark background?

Set the --scroll-fade-color CSS variable to match your panel background color, e.g. style={{ '--scroll-fade-color': '#1a1a2e' }}. For transparent/blurred panels, switch to the mask-image approach described in the shadow fade section.

Does this work with horizontal scrolling too?

The component as written is vertical only. For horizontal, swap overflow-y to overflow-x, flip the gradient directions, and track scrollLeft / clientWidth / scrollWidth instead of the vertical equivalents.

Free components in 41 styles
React & Tailwind, copy-paste ready.
Browse β†’

Read next

React UI Components Complete Reference: 60+ Patterns with Code β†’Stepper Component in React: Multi-Step Forms and Onboarding β†’Skeleton Loader in React: Pulse Animation and Smart Loading States β†’Scroll Progress Indicator in React: Bar, Circle and Sidebar Dots β†’