# Parallax Floating

> Elements float at different speeds based on cursor position, creating a depth illusion through independent parallax layers.

Docs: https://ui.cnippet.dev/motion/scroll-animations/parallax-floating

```tsx
import {
  FloatingElement,
  ParallaxFloating,
} from "@/registry/default/motion/parallax-floating";

export default function ParallaxFloatingShapes() {
  return (
    <div className="relative flex min-h-50 items-center justify-center overflow-hidden rounded-xl bg-gradient-to-br from-violet-500/5 via-transparent to-indigo-500/5">
      <ParallaxFloating sensitivity={1}>
        <FloatingElement className="top-[15%] left-[8%]" depth={0.5}>
          <div className="h-10 w-10 rounded-xl border border-violet-500/20 bg-violet-500/10" />
        </FloatingElement>
        <FloatingElement className="top-[20%] right-[12%]" depth={1.5}>
          <div className="h-5 w-5 rounded-full bg-pink-500/30" />
        </FloatingElement>
        <FloatingElement className="bottom-[20%] left-[15%]" depth={2.5}>
          <div className="h-7 w-7 rotate-45 rounded-md bg-indigo-500/20" />
        </FloatingElement>
        <FloatingElement className="right-[8%] bottom-[25%]" depth={1}>
          <div className="h-12 w-12 rounded-2xl bg-sky-500/15" />
        </FloatingElement>
        <FloatingElement className="top-[10%] left-[40%]" depth={3}>
          <div className="h-3 w-3 rounded-full bg-emerald-500/40" />
        </FloatingElement>
      </ParallaxFloating>
      <div className="relative z-10 text-center">
        <p className="font-semibold text-muted-foreground text-xs uppercase tracking-widest">
          Move your cursor
        </p>
        <h2 className="mt-1 font-bold text-2xl text-foreground">
          Depth in motion
        </h2>
        <p className="mt-1 text-muted-foreground text-sm">
          Each layer floats at a different speed
        </p>
      </div>
    </div>
  );
}
```

## Installation

**CLI**

```bash
npx shadcn@latest add @cnippet/parallax-floating
```

**Manual**

1. Install the following dependencies:

```bash
npm install motion
```

2. Copy and paste the following code into your project.

`components/motion/parallax-floating.tsx`

```tsx
"use client";

import { useAnimationFrame, useReducedMotion } from "motion/react";
import {
  createContext,
  type ReactNode,
  useCallback,
  useContext,
  useEffect,
  useRef,
} from "react";
import { cn } from "@/lib/utils";

function useMousePositionRef(
  containerRef?: React.RefObject<HTMLElement | SVGElement | null>,
) {
  const positionRef = useRef({ x: 0, y: 0 });

  useEffect(() => {
    const updatePosition = (x: number, y: number) => {
      if (containerRef?.current) {
        const rect = containerRef.current.getBoundingClientRect();
        positionRef.current = { x: x - rect.left, y: y - rect.top };
      } else {
        positionRef.current = { x, y };
      }
    };

    const handleMouseMove = (ev: MouseEvent) =>
      updatePosition(ev.clientX, ev.clientY);
    const handleTouchMove = (ev: TouchEvent) => {
      const touch = ev.touches[0];
      if (touch) updatePosition(touch.clientX, touch.clientY);
    };

    window.addEventListener("mousemove", handleMouseMove);
    window.addEventListener("touchmove", handleTouchMove);
    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("touchmove", handleTouchMove);
    };
  }, [containerRef]);

  return positionRef;
}

interface FloatingContextType {
  registerElement: (id: string, element: HTMLDivElement, depth: number) => void;
  unregisterElement: (id: string) => void;
}

const FloatingContext = createContext<FloatingContextType | null>(null);

export interface ParallaxFloatingProps {
  children: ReactNode;
  className?: string;
  sensitivity?: number;
  easingFactor?: number;
}

export function ParallaxFloating({
  children,
  className,
  sensitivity = 1,
  easingFactor = 0.05,
}: ParallaxFloatingProps) {
  const reduceMotion = useReducedMotion();
  const containerRef = useRef<HTMLDivElement>(null);
  const elementsMap = useRef(
    new Map<
      string,
      {
        element: HTMLDivElement;
        depth: number;
        currentPosition: { x: number; y: number };
      }
    >(),
  );
  const mousePositionRef = useMousePositionRef(containerRef);

  const registerElement = useCallback(
    (id: string, element: HTMLDivElement, depth: number) => {
      elementsMap.current.set(id, {
        currentPosition: { x: 0, y: 0 },
        depth,
        element,
      });
    },
    [],
  );

  const unregisterElement = useCallback((id: string) => {
    elementsMap.current.delete(id);
  }, []);

  useAnimationFrame(() => {
    if (!containerRef.current || reduceMotion) return;

    elementsMap.current.forEach((data) => {
      const strength = (data.depth * sensitivity) / 20;
      const newTargetX = mousePositionRef.current.x * strength;
      const newTargetY = mousePositionRef.current.y * strength;

      data.currentPosition.x +=
        (newTargetX - data.currentPosition.x) * easingFactor;
      data.currentPosition.y +=
        (newTargetY - data.currentPosition.y) * easingFactor;

      data.element.style.transform = `translate3d(${data.currentPosition.x}px, ${data.currentPosition.y}px, 0)`;
    });
  });

  return (
    <FloatingContext.Provider value={{ registerElement, unregisterElement }}>
      <div
        className={cn("absolute top-0 left-0 h-full w-full", className)}
        ref={containerRef}
      >
        {children}
      </div>
    </FloatingContext.Provider>
  );
}

export interface FloatingElementProps {
  children: ReactNode;
  className?: string;
  depth?: number;
}

export function FloatingElement({
  children,
  className,
  depth = 1,
}: FloatingElementProps) {
  const elementRef = useRef<HTMLDivElement>(null);
  const idRef = useRef(Math.random().toString(36).substring(7));
  const context = useContext(FloatingContext);

  useEffect(() => {
    if (!elementRef.current || !context) return;
    const id = idRef.current;
    context.registerElement(id, elementRef.current, depth ?? 0.01);
    return () => context.unregisterElement(id);
  }, [depth, context]);

  return (
    <div
      className={cn("absolute will-change-transform", className)}
      ref={elementRef}
    >
      {children}
    </div>
  );
}
```

3. Update the import paths to match your project setup.

## Usage

```tsx
import {
  FloatingElement,
  ParallaxFloating,
} from "@/components/motion/parallax-floating";
```

```tsx
<div className="relative h-96 w-full overflow-hidden">
  <ParallaxFloating sensitivity={1}>
    <FloatingElement className="left-[10%] top-[20%]" depth={0.5}>
      <div className="h-10 w-10 rounded-xl bg-violet-500/20" />
    </FloatingElement>
    <FloatingElement className="right-[15%] top-[15%]" depth={2}>
      <div className="h-6 w-6 rounded-full bg-pink-500/30" />
    </FloatingElement>
  </ParallaxFloating>
  <div className="relative z-10">Your content here</div>
</div>
```

## Anatomy

```tsx
<div className="relative h-96 overflow-hidden"> {/* your sized, positioned container */}
  <ParallaxFloating sensitivity={1}> {/* fills the container, tracks the cursor */}
    <FloatingElement depth={2} className="left-[10%] top-[20%]">…</FloatingElement> {/* absolutely positioned */}
  </ParallaxFloating>
</div>
```

## Good to know

- `ParallaxFloating` fills its parent (`absolute inset-0`), so put it inside a sized container with `position: relative`.
- Position each `FloatingElement` with `className` (`left-*`, `top-*`). Higher `depth` values move further with the cursor.
- It reacts to the mouse, so there's no effect on touch screens.
- When the user has turned on reduced motion, the elements stay in place and do not follow the cursor.

## Props

### ParallaxFloating

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `children` | `ReactNode` | — | `FloatingElement` instances |
| `sensitivity` | `number` | `1` | Multiplier for the overall movement intensity |
| `easingFactor` | `number` | `0.05` | Lerp factor controlling how smoothly elements follow the cursor |
| `className` | `string` | — | Class applied to the container (defaults to `absolute inset-0`) |

### FloatingElement

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `children` | `ReactNode` | — | Content to float |
| `depth` | `number` | `1` | Parallax depth — higher values move more |
| `className` | `string` | — | Positioning classes (e.g. `left-[10%] top-[20%]`) |

## Examples

### Floating Shapes

Geometric shapes at varying depths follow the cursor, each moving at a different speed.

```tsx
import {
  FloatingElement,
  ParallaxFloating,
} from "@/registry/default/motion/parallax-floating";

export default function ParallaxFloatingShapes() {
  return (
    <div className="relative flex min-h-50 items-center justify-center overflow-hidden rounded-xl bg-gradient-to-br from-violet-500/5 via-transparent to-indigo-500/5">
      <ParallaxFloating sensitivity={1}>
        <FloatingElement className="top-[15%] left-[8%]" depth={0.5}>
          <div className="h-10 w-10 rounded-xl border border-violet-500/20 bg-violet-500/10" />
        </FloatingElement>
        <FloatingElement className="top-[20%] right-[12%]" depth={1.5}>
          <div className="h-5 w-5 rounded-full bg-pink-500/30" />
        </FloatingElement>
        <FloatingElement className="bottom-[20%] left-[15%]" depth={2.5}>
          <div className="h-7 w-7 rotate-45 rounded-md bg-indigo-500/20" />
        </FloatingElement>
        <FloatingElement className="right-[8%] bottom-[25%]" depth={1}>
          <div className="h-12 w-12 rounded-2xl bg-sky-500/15" />
        </FloatingElement>
        <FloatingElement className="top-[10%] left-[40%]" depth={3}>
          <div className="h-3 w-3 rounded-full bg-emerald-500/40" />
        </FloatingElement>
      </ParallaxFloating>
      <div className="relative z-10 text-center">
        <p className="font-semibold text-muted-foreground text-xs uppercase tracking-widest">
          Move your cursor
        </p>
        <h2 className="mt-1 font-bold text-2xl text-foreground">
          Depth in motion
        </h2>
        <p className="mt-1 text-muted-foreground text-sm">
          Each layer floats at a different speed
        </p>
      </div>
    </div>
  );
}
```

### Floating Card

A card with floating glow blobs and dot accents at independent depth layers.

```tsx
import {
  FloatingElement,
  ParallaxFloating,
} from "@/registry/default/motion/parallax-floating";

export default function ParallaxFloatingCard() {
  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <div className="relative h-52 w-full max-w-xs overflow-hidden rounded-2xl border border-border bg-card shadow-md">
        <ParallaxFloating sensitivity={0.8}>
          <FloatingElement className="top-[-30px] right-[-30px]" depth={3}>
            <div className="h-36 w-36 rounded-full bg-violet-500/10 blur-3xl" />
          </FloatingElement>
          <FloatingElement className="bottom-[-20px] left-[-20px]" depth={2}>
            <div className="h-28 w-28 rounded-full bg-blue-500/10 blur-2xl" />
          </FloatingElement>
          <FloatingElement className="top-5 right-5" depth={1.5}>
            <div className="h-2.5 w-2.5 rounded-full bg-violet-400/80" />
          </FloatingElement>
          <FloatingElement className="top-8 left-6" depth={1}>
            <div className="h-1.5 w-1.5 rounded-full bg-pink-400/80" />
          </FloatingElement>
        </ParallaxFloating>
        <div className="relative z-10 flex h-full flex-col justify-end p-5">
          <span className="font-semibold text-primary text-xs uppercase tracking-widest">
            Featured
          </span>
          <h3 className="mt-1 font-bold text-foreground text-lg">
            Hover to shift layers
          </h3>
          <p className="mt-0.5 text-muted-foreground text-xs">
            Blobs and dots float independently
          </p>
        </div>
      </div>
    </div>
  );
}
```

### Floating Symbols

Abstract symbols drift at different depths — useful as decorative hero backgrounds.

```tsx
import {
  FloatingElement,
  ParallaxFloating,
} from "@/registry/default/motion/parallax-floating";

const symbols = [
  { char: "◈", cls: "left-[6%] top-[12%]", depth: 0.5, size: "text-4xl" },
  { char: "⬡", cls: "left-[28%] top-[30%]", depth: 1.5, size: "text-2xl" },
  { char: "◎", cls: "right-[18%] top-[18%]", depth: 2.5, size: "text-3xl" },
  { char: "◇", cls: "left-[12%] bottom-[22%]", depth: 2, size: "text-2xl" },
  { char: "△", cls: "right-[6%] bottom-[18%]", depth: 1, size: "text-4xl" },
  { char: "□", cls: "right-[38%] bottom-[38%]", depth: 3, size: "text-xl" },
  { char: "⬟", cls: "right-[10%] top-[45%]", depth: 1.8, size: "text-2xl" },
];

export default function ParallaxFloatingSymbols() {
  return (
    <div className="relative flex min-h-50 items-center justify-center overflow-hidden rounded-xl bg-muted/20">
      <ParallaxFloating sensitivity={1.5}>
        {symbols.map(({ char, cls, depth, size }) => (
          <FloatingElement className={cls} depth={depth} key={char}>
            <span className={`${size} select-none text-foreground/15`}>
              {char}
            </span>
          </FloatingElement>
        ))}
      </ParallaxFloating>
      <p className="relative z-10 text-center font-medium text-muted-foreground text-sm">
        Cursor drives each symbol at a unique depth
      </p>
    </div>
  );
}
```
