Skip to content
Atoms

Avatar group

Stacked avatars that spread on hover.

Primitive

Installation

Primitive
  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/, installs radix-ui@base-ui/react and the colour tokens go into your CSS. This is the Radix build. Drop --radix for Base UI.This is the Base UI build, the default. Want Radix? Add --radix.

    $ pnpm dlx asta-ui@latest add avatar-group --radix

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/avatar-group.json

  2. Or install the package

    Don’t want the file? Import from asta-uiasta-ui/base and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui radix-ui @base-ui/react
    import { AvatarStack } from "asta-ui";
    import { AvatarStack } from "asta-ui/base";
  3. Or copy it by hand

    Install radix-ui@base-ui/react, then copy these files. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
    import { avatarFill, initials } from "@/components/kit/avatar";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    export interface AvatarStackPerson {
      name: string;
      /** Image URL. Falls back to initials if missing or it fails to load. */
      src?: string;
    }
    
    export interface AvatarStackProps {
      people: AvatarStackPerson[];
      /** Avatars shown before the rest fold into "+N". */
      max?: number;
      size?: "sm" | "md" | "lg";
      /** Makes "+N" a button, e.g. to open the full member list. */
      onOverflowClick?: () => void;
      /** Accessible name for the group. Defaults to "N people". */
      label?: string;
      className?: string;
    }
    
    const SIZES = {
      sm: { box: 28, text: "text-[11px]", overlap: -8 },
      md: { box: 36, text: "text-[13px]", overlap: -10 },
      lg: { box: 44, text: "text-[15px]", overlap: -12 },
    };
    
    function Face({ person, text }: { person: AvatarStackPerson; text: string }) {
      const [broken, setBroken] = useState<string | null>(null);
      const showImg = person.src && broken !== person.src;
      return (
        <span className={cx("flex h-full w-full select-none items-center justify-center overflow-hidden rounded-full font-medium tracking-[-0.02em]", !showImg && avatarFill(person.name), text)}>
          {showImg ? <img src={person.src} alt="" draggable={false} onError={() => setBroken(person.src!)} className="h-full w-full object-cover" /> : initials(person.name)}
        </span>
      );
    }
    
    function Tip({ children }: { children: string }) {
      return (
        <span
          aria-hidden
          className="pointer-events-none absolute bottom-full left-1/2 z-20 mb-2 max-w-[220px] -translate-x-1/2 translate-y-1 truncate whitespace-nowrap rounded-[6px] bg-ink px-2 py-1 text-[12px] font-medium leading-none text-paper opacity-0 transition-[opacity,translate] duration-200 ease-[cubic-bezier(.16,1,.3,1)] group-hover/face:translate-y-0 group-hover/face:opacity-100 group-focus-visible/face:translate-y-0 group-focus-visible/face:opacity-100 motion-reduce:transition-none"
        >
          {children}
        </span>
      );
    }
    
    /**
     * Overlapping avatars. Hover the stack and it spreads a little, hover one face and it lifts and shows the
     * name. People past `max` fold into "+N". The stack is one tab stop and arrow keys move between faces.
     */
    export function AvatarStack({ people, max = 4, size = "md", onOverflowClick, label, className }: AvatarStackProps) {
      const s = SIZES[size];
      const cap = Math.max(1, max);
      // Showing "+1" would hide a face that fits in the same space, so only fold two or more.
      const shown = people.length - cap === 1 ? people : people.slice(0, cap);
      const rest = people.slice(shown.length);
      const items = shown.length + (rest.length ? 1 : 0);
      const restNames = rest.map((p) => p.name);
      const restText = restNames.length > 3 ? `${restNames.slice(0, 3).join(", ")} and ${restNames.length - 3} more` : restNames.join(", ");
    
      const root = useRef<HTMLUListElement>(null);
      const [focusIdx, setFocusIdx] = useState(0);
      const stop = Math.min(focusIdx, items - 1);
    
      const onKey = (e: KeyboardEvent) => {
        let i = stop;
        if (e.key === "ArrowRight" || e.key === "ArrowDown") i = Math.min(items - 1, stop + 1);
        else if (e.key === "ArrowLeft" || e.key === "ArrowUp") i = Math.max(0, stop - 1);
        else if (e.key === "Home") i = 0;
        else if (e.key === "End") i = items - 1;
        else return;
        e.preventDefault();
        setFocusIdx(i);
        root.current?.querySelectorAll<HTMLElement>("[data-face]")[i]?.focus();
      };
    
      const face = "group/face relative block rounded-full outline-none shadow-[0_0_0_2px_var(--color-paper)] focus-visible:shadow-[0_0_0_2px_var(--color-paper),0_0_0_4px_var(--color-brand)]";
      const li = (i: number) =>
        cx(
          "relative transition-[translate] duration-500 ease-[cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none",
          "group-hover/stack:translate-x-[calc(var(--i)*5px)] group-focus-within/stack:translate-x-[calc(var(--i)*5px)]",
          "hover:z-10 focus-within:z-10 [&:hover>*]:-translate-y-1 [&:focus-within>*]:-translate-y-1",
          i > 0 && "-ml-[var(--o)]",
        );
      const vars = (i: number) => ({ "--i": i, "--o": `${-s.overlap}px` }) as CSSProperties;
    
      // "+N" is a button when it does something, else a labelled image.
      const Overflow = onOverflowClick ? "button" : "span";
    
      if (!people.length) return null;
    
      return (
        <ul ref={root} aria-label={label ?? `${people.length} ${people.length === 1 ? "person" : "people"}`} onKeyDown={onKey} className={cx("group/stack flex items-center", className)}>
          {shown.map((p, i) => (
            <li key={`${p.name}-${i}`} className={li(i)} style={vars(i)}>
              <span
                data-face
                role="img"
                aria-label={p.name}
                tabIndex={i === stop ? 0 : -1}
                onFocus={() => setFocusIdx(i)}
                className={cx(face, "transition-[translate] duration-300 ease-[cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none")}
                style={{ width: s.box, height: s.box }}
              >
                <Face person={p} text={s.text} />
                <Tip>{p.name}</Tip>
              </span>
            </li>
          ))}
          {rest.length > 0 && (
            <li className={li(shown.length)} style={vars(shown.length)}>
              <Overflow
                {...(onOverflowClick ? { type: "button" as const, onClick: onOverflowClick } : { role: "img" })}
                data-face
                aria-label={`${rest.length} more: ${restText}`}
                tabIndex={shown.length === stop ? 0 : -1}
                onFocus={() => setFocusIdx(shown.length)}
                className={cx(
                  face,
                  "flex items-center justify-center bg-paper-2 font-medium tabular-nums text-ink-2 duration-300 ease-[cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none",
                  onOverflowClick ? "transition-[translate,color] hover:text-ink" : "transition-[translate]",
                  s.text,
                )}
                style={{ width: s.box, height: s.box }}
              >
                +{rest.length}
                <Tip>{restText}</Tip>
              </Overflow>
            </li>
          )}
        </ul>
      );
    }
    
    export default AvatarStack;
    
    "use client";
    
    import { useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
    import { avatarFill, initials } from "@/components/kit/base/avatar";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    export interface AvatarStackPerson {
      name: string;
      /** Image URL. Falls back to initials if missing or it fails to load. */
      src?: string;
    }
    
    export interface AvatarStackProps {
      people: AvatarStackPerson[];
      /** Avatars shown before the rest fold into "+N". */
      max?: number;
      size?: "sm" | "md" | "lg";
      /** Makes "+N" a button, e.g. to open the full member list. */
      onOverflowClick?: () => void;
      /** Accessible name for the group. Defaults to "N people". */
      label?: string;
      className?: string;
    }
    
    const SIZES = {
      sm: { box: 28, text: "text-[11px]", overlap: -8 },
      md: { box: 36, text: "text-[13px]", overlap: -10 },
      lg: { box: 44, text: "text-[15px]", overlap: -12 },
    };
    
    function Face({ person, text }: { person: AvatarStackPerson; text: string }) {
      const [broken, setBroken] = useState<string | null>(null);
      const showImg = person.src && broken !== person.src;
      return (
        <span className={cx("flex h-full w-full select-none items-center justify-center overflow-hidden rounded-full font-medium tracking-[-0.02em]", !showImg && avatarFill(person.name), text)}>
          {showImg ? <img src={person.src} alt="" draggable={false} onError={() => setBroken(person.src!)} className="h-full w-full object-cover" /> : initials(person.name)}
        </span>
      );
    }
    
    function Tip({ children }: { children: string }) {
      return (
        <span
          aria-hidden
          className="pointer-events-none absolute bottom-full left-1/2 z-20 mb-2 max-w-[220px] -translate-x-1/2 translate-y-1 truncate whitespace-nowrap rounded-[6px] bg-ink px-2 py-1 text-[12px] font-medium leading-none text-paper opacity-0 transition-[opacity,translate] duration-200 ease-[cubic-bezier(.16,1,.3,1)] group-hover/face:translate-y-0 group-hover/face:opacity-100 group-focus-visible/face:translate-y-0 group-focus-visible/face:opacity-100 motion-reduce:transition-none"
        >
          {children}
        </span>
      );
    }
    
    /**
     * Overlapping avatars. Hover the stack and it spreads a little, hover one face and it lifts and shows the
     * name. People past `max` fold into "+N". The stack is one tab stop and arrow keys move between faces.
     */
    export function AvatarStack({ people, max = 4, size = "md", onOverflowClick, label, className }: AvatarStackProps) {
      const s = SIZES[size];
      const cap = Math.max(1, max);
      // Showing "+1" would hide a face that fits in the same space, so only fold two or more.
      const shown = people.length - cap === 1 ? people : people.slice(0, cap);
      const rest = people.slice(shown.length);
      const items = shown.length + (rest.length ? 1 : 0);
      const restNames = rest.map((p) => p.name);
      const restText = restNames.length > 3 ? `${restNames.slice(0, 3).join(", ")} and ${restNames.length - 3} more` : restNames.join(", ");
    
      const root = useRef<HTMLUListElement>(null);
      const [focusIdx, setFocusIdx] = useState(0);
      const stop = Math.min(focusIdx, items - 1);
    
      const onKey = (e: KeyboardEvent) => {
        let i = stop;
        if (e.key === "ArrowRight" || e.key === "ArrowDown") i = Math.min(items - 1, stop + 1);
        else if (e.key === "ArrowLeft" || e.key === "ArrowUp") i = Math.max(0, stop - 1);
        else if (e.key === "Home") i = 0;
        else if (e.key === "End") i = items - 1;
        else return;
        e.preventDefault();
        setFocusIdx(i);
        root.current?.querySelectorAll<HTMLElement>("[data-face]")[i]?.focus();
      };
    
      const face = "group/face relative block rounded-full outline-none shadow-[0_0_0_2px_var(--color-paper)] focus-visible:shadow-[0_0_0_2px_var(--color-paper),0_0_0_4px_var(--color-brand)]";
      const li = (i: number) =>
        cx(
          "relative transition-[translate] duration-500 ease-[cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none",
          "group-hover/stack:translate-x-[calc(var(--i)*5px)] group-focus-within/stack:translate-x-[calc(var(--i)*5px)]",
          "hover:z-10 focus-within:z-10 [&:hover>*]:-translate-y-1 [&:focus-within>*]:-translate-y-1",
          i > 0 && "-ml-[var(--o)]",
        );
      const vars = (i: number) => ({ "--i": i, "--o": `${-s.overlap}px` }) as CSSProperties;
    
      // "+N" is a button when it does something, else a labelled image.
      const Overflow = onOverflowClick ? "button" : "span";
    
      if (!people.length) return null;
    
      return (
        <ul ref={root} aria-label={label ?? `${people.length} ${people.length === 1 ? "person" : "people"}`} onKeyDown={onKey} className={cx("group/stack flex items-center", className)}>
          {shown.map((p, i) => (
            <li key={`${p.name}-${i}`} className={li(i)} style={vars(i)}>
              <span
                data-face
                role="img"
                aria-label={p.name}
                tabIndex={i === stop ? 0 : -1}
                onFocus={() => setFocusIdx(i)}
                className={cx(face, "transition-[translate] duration-300 ease-[cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none")}
                style={{ width: s.box, height: s.box }}
              >
                <Face person={p} text={s.text} />
                <Tip>{p.name}</Tip>
              </span>
            </li>
          ))}
          {rest.length > 0 && (
            <li className={li(shown.length)} style={vars(shown.length)}>
              <Overflow
                {...(onOverflowClick ? { type: "button" as const, onClick: onOverflowClick } : { role: "img" })}
                data-face
                aria-label={`${rest.length} more: ${restText}`}
                tabIndex={shown.length === stop ? 0 : -1}
                onFocus={() => setFocusIdx(shown.length)}
                className={cx(
                  face,
                  "flex items-center justify-center bg-paper-2 font-medium tabular-nums text-ink-2 duration-300 ease-[cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none",
                  onOverflowClick ? "transition-[translate,color] hover:text-ink" : "transition-[translate]",
                  s.text,
                )}
                style={{ width: s.box, height: s.box }}
              >
                +{rest.length}
                <Tip>{restText}</Tip>
              </Overflow>
            </li>
          )}
        </ul>
      );
    }
    
    export default AvatarStack;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Avatar group component to my project.
    
    Stacked avatars that spread on hover.
    It includes: AvatarStack, overflow, tooltips, sm, md, lg, keys.
    
    Install it (Radix build):
    ```sh
    pnpm dlx asta-ui@latest add avatar-group --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/avatar-group.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { AvatarStack } from "@/components/astabyte/avatar-group";
    ```
    
    Usage example and props: https://ui.astabyte.com/avatar-group
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Radix primitives from the radix-ui package).
    - Stay on Radix: install other Astabyte UI components with `--radix` so the project uses one primitive library.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
    Add the Astabyte UI Avatar group component to my project.
    
    Stacked avatars that spread on hover.
    It includes: AvatarStack, overflow, tooltips, sm, md, lg, keys.
    
    Install it (Base UI build):
    ```sh
    pnpm dlx asta-ui@latest add avatar-group
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/avatar-group.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { AvatarStack } from "@/components/astabyte/avatar-group";
    ```
    
    Usage example and props: https://ui.astabyte.com/avatar-group
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Base UI primitives from the @base-ui/react package).
    - Stay on Base UI: install other Astabyte UI components without `--radix` so the project uses one primitive library.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <div style="display:flex;flex-wrap:wrap;align-items:center;gap:12px">
    <ul class="asta-avatar-group" aria-label="6 people"><li class="asta-avatar-group-item" style="--i:0"><span class="asta-avatar-group-face" role="img" aria-label="Ada Lovelace"><span class="asta-avatar-face">AL</span><span class="asta-avatar-tip" aria-hidden="true">Ada Lovelace</span></span></li><li class="asta-avatar-group-item" style="--i:1"><span class="asta-avatar-group-face" role="img" aria-label="Grace Hopper"><span class="asta-avatar-face asta-avatar-brand">GH</span><span class="asta-avatar-tip" aria-hidden="true">Grace Hopper</span></span></li><li class="asta-avatar-group-item" style="--i:2"><span class="asta-avatar-group-face" role="img" aria-label="Alan Turing"><span class="asta-avatar-face asta-avatar-soft">AT</span><span class="asta-avatar-tip" aria-hidden="true">Alan Turing</span></span></li><li class="asta-avatar-group-item" style="--i:3"><span class="asta-avatar-group-face" role="img" aria-label="Linus T"><span class="asta-avatar-face asta-avatar-tint">LT</span><span class="asta-avatar-tip" aria-hidden="true">Linus T</span></span></li><li class="asta-avatar-group-item" style="--i:4"><span class="asta-avatar-group-face asta-avatar-group-more" role="img" aria-label="2 more: Ken T, Rob P">+2<span class="asta-avatar-tip" aria-hidden="true">Ken T, Rob P</span></span></li></ul>
    </div>

Usage

The demo above, as code.

"use client";

import { useState } from "react";
import { AvatarStack } from "@/components/astabyte/avatar-group";

const TEAM = [
  { name: "Maya Rahman" },
  { name: "Tomás Kirsch" },
  { name: "Ayu Lestari" },
  { name: "Jonah Weiss" },
  { name: "Lena Okafor" },
  { name: "Ravi Menon" },
  { name: "Sofia Lund" },
  { name: "Kenji Ito" },
];

export default function AvatarGroupDemo() {
  const [all, setAll] = useState(false);

  return (
    <div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
      <div className="flex w-full max-w-sm flex-col gap-8">
        <div className="rounded-xl bg-paper-2 p-5">
          <p className="text-[12px] text-mute">Q3 launch · Design</p>
          <p className="mt-1 text-[15px] font-medium tracking-[-0.01em] text-ink">Homepage refresh</p>
          <div className="mt-5 flex items-center justify-between gap-4">
            <AvatarStack label="Project members" people={TEAM} max={all ? TEAM.length : 4} onOverflowClick={() => setAll(true)} />
            {all ? (
              <button type="button" onClick={() => setAll(false)} className="rounded-[7px] px-2 py-1 text-[12.5px] text-mute outline-none transition-colors hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50">
                Collapse
              </button>
            ) : (
              <span className="text-[12.5px] text-mute">{TEAM.length} members</span>
            )}
          </div>
        </div>

        <div className="flex flex-col gap-4 px-1">
          <div className="flex items-center justify-between gap-4">
            <p className="text-[14px] text-ink-2">Viewing now</p>
            <AvatarStack size="sm" people={TEAM.slice(0, 3)} label="3 people viewing" />
          </div>
          <div className="flex items-center justify-between gap-4">
            <p className="text-[14px] text-ink-2">Reviewers</p>
            <AvatarStack size="lg" max={3} people={TEAM.slice(2)} label="Reviewers" />
          </div>
        </div>

        <p className="text-center text-[12.5px] text-mute">Hover the stack to spread it. Tab in, then use the arrow keys to read each name.</p>
      </div>
    </div>
  );
}