DocumentationCollapse

Collapse

Height collapse with a real exit animation, held open until the keyframes finish.

Basic

Place content inside the component. Native attributes and events use Svelte spelling, such as onclick, and bind:element gives you the root DOM element.

Quick start

Add to your project

Copy the component and everything it needs into your Svelte 5 project.

RecommendedUse the shadcn-svelte CLI
npx shadcn-svelte@1.8.0 add https://kida-ui.onrender.com/r/svelte/collapse.json

Run this from a project with components.json. The CLI creates all required files and installs the declared runtime dependencies. New to shadcn? Follow theinstallation guide first.

Files land in src/lib/components/ui/kida by default. SvelteKit 3 projects import them through #lib; SvelteKit 2 and Vite projects use $lib, as in the examples here.

View registry JSON
Copy manually7 files

1. Install runtime dependencies

npm install @zag-js/presence@1.43.3 @zag-js/svelte@1.43.3

2. Create the source files

Keep this directory structure so the component's relative imports continue to work.

src/lib/components/ui/kida/collapse.svelte
<script lang="ts">
import './collapse.css'
import {
  type CollapseSizeObserver,
  observeCollapseSize,
  prefersReducedMotion,
} from './collapse.motion.js'
import * as presence from '@zag-js/presence'
import { normalizeProps, useMachine } from '@zag-js/svelte'
import { untrack } from 'svelte'
import type { CollapseProps } from './collapse.types.js'

let { open, onExitComplete, element = $bindable(null), children, ...rest }: CollapseProps = $props()

const service = useMachine(presence.machine, () => ({
  present: open,
  onExitComplete: () => onExitComplete?.(),
}))
const api = $derived(presence.connect(service, normalizeProps))
let content = $state<HTMLDivElement | null>(null)
let size: CollapseSizeObserver | undefined
const root = $derived(element)

$effect(() => {
  const node = root
  untrack(() => api.setNode(node))
})

$effect(() => {
  const node = root
  const inner = content
  if (!node || !inner) return
  const observer = observeCollapseSize(node, inner)
  size = observer
  return () => {
    observer.disconnect()
    if (size === observer) size = undefined
  }
})

$effect(() => {
  void { ...rest }
  untrack(() => size?.measure())
})

$effect(() => {
  if (!open) untrack(() => prefersReducedMotion() && api.unmount())
})
</script>

{#if api.present}
  <div
    {...rest}
    bind:this={element}
    data-kida-collapse=""
    data-state={open ? 'open' : 'closed'}
    data-skip-animation={api.skip ? '' : undefined}
  >
    <div bind:this={content}>{@render children?.()}</div>
  </div>
{/if}
src/lib/components/ui/kida/collapse.types.ts
import type { HTMLAttributes } from 'svelte/elements';

export interface CollapseProps extends HTMLAttributes<HTMLDivElement> {
    open: boolean;
    onExitComplete?: () => void;
    element?: HTMLDivElement | null;
}
src/lib/components/ui/kida/collapse-size.motion.ts
interface Frame {
  paddingTop: number
  paddingBottom: number
  borderTopWidth: number
  borderBottomWidth: number
  borderBox: boolean
}

export interface CollapseSizeObserver {
  /** Remeasure after the adapter updates root styles or content. */
  measure(): void
  /** Stop observation when presence removes the node or the adapter unmounts. */
  disconnect(): void
}

/**
 * Measure the natural content height and root frame into the shared Collapse CSS variables.
 * The adapter owns presence; this helper owns layout and container-size observation.
 */
export function observeCollapseSize(root: HTMLElement, content: HTMLElement): CollapseSizeObserver {
  let frame: Frame | undefined
  let active = true

  const readFrame = (): Frame => {
    // Opening keyframes zero the root's frame. Suppress them across this read so we measure
    // authored padding/borders rather than the animated values.
    const restore = root.style.animationName
    root.style.animationName = 'none'
    try {
      const style = getComputedStyle(root)
      return {
        paddingTop: Number.parseFloat(style.paddingTop),
        paddingBottom: Number.parseFloat(style.paddingBottom),
        borderTopWidth: Number.parseFloat(style.borderTopWidth),
        borderBottomWidth: Number.parseFloat(style.borderBottomWidth),
        borderBox: style.boxSizing === 'border-box',
      }
    } finally {
      root.style.animationName = restore
    }
  }

  const measure = () => {
    if (!active) return
    // Keep the frame cached during motion: suppressing a running animation to read it would
    // restart the animation. Refresh when settled so authored style changes still take effect.
    if (!frame || root.getAnimations().length === 0) frame = readFrame()

    // CSS height uses the root's box-sizing. Only border-box includes the root's own frame.
    let height = content.getBoundingClientRect().height
    if (frame.borderBox) {
      height +=
        frame.paddingTop + frame.paddingBottom + frame.borderTopWidth + frame.borderBottomWidth
    }

    root.style.setProperty('--kida-collapse-height', `${height}px`)
    root.style.setProperty('--kida-collapse-padding-top', `${frame.paddingTop}px`)
    root.style.setProperty('--kida-collapse-padding-bottom', `${frame.paddingBottom}px`)
    root.style.setProperty('--kida-collapse-border-top-width', `${frame.borderTopWidth}px`)
    root.style.setProperty('--kida-collapse-border-bottom-width', `${frame.borderBottomWidth}px`)
  }

  measure()
  const observer = new ResizeObserver(measure)
  observer.observe(content)

  return {
    measure,
    disconnect() {
      active = false
      observer.disconnect()
    },
  }
}
src/lib/components/ui/kida/collapse.motion.ts
export { type CollapseSizeObserver, observeCollapseSize } from './collapse-size.motion.js'
export { prefersReducedMotion } from './reduced-motion.motion.js'
src/lib/components/ui/kida/reduced-motion.motion.ts
const QUERY = '(prefers-reduced-motion: reduce)'

/**
 * Whether the user has asked for reduced motion.
 *
 * SSR-safe: returns `false` when there is no `window`, matching the CSS default
 * (the `prefers-reduced-motion` media query in `@kida-ui/styles` is the real guard;
 * this is for the JS-driven paths that CSS cannot express).
 */
export function prefersReducedMotion(): boolean {
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false
  return window.matchMedia(QUERY).matches
}

/**
 * Subscribe to changes of the reduced-motion preference.
 * Returns an unsubscribe function. No-op (and immediately unsubscribable) on the server.
 */
export function watchReducedMotion(onChange: (reduced: boolean) => void): () => void {
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return () => {}

  const list = window.matchMedia(QUERY)
  const handler = (event: MediaQueryListEvent) => onChange(event.matches)
  list.addEventListener('change', handler)
  return () => list.removeEventListener('change', handler)
}
src/lib/components/ui/kida/collapse.css
@import './tokens.css';

/*
 * Collapse — the CSS-driven half of ADR D5.
 *
 * `@zag-js/presence` reads the computed animation on this element to decide how long to
 * keep it mounted, so the exit transition MUST be a CSS animation. If it were a JS
 * animation the node would be torn out on the first frame.
 *
 * Height is animated rather than transform, which is not compositor-friendly — the usual
 * and unavoidable trade for collapsing to natural height. Content inside should animate
 * with opacity/transform if it needs motion of its own.
 */

[data-kida-collapse] {
  overflow: hidden;
}

[data-kida-collapse][data-state="open"] {
  animation: kida-collapse-open var(--kida-collapse-duration, var(--kida-duration-md))
    var(--kida-collapse-ease, var(--kida-ease-out));
}

/*
 * Deliberately not `--kida-ease-in`. Both of that curve's control points sit at y=0, so
 * it is pinned near zero for most of its length: measured over the old 150ms close, the
 * panel was 4% collapsed at the halfway mark and dropped the last 53% inside ~26ms —
 * a frame and a half. It reads as the panel blinking out rather than closing. Reversing
 * the open curve is exact on paper and wrong in the eye, because the fast part lands
 * where nobody is still looking. Here the shrinking IS the information, so it has to be
 * legible, which also means matching the open duration instead of halving it.
 *
 * `forwards` holds the final frame: presence unmounts on `animationend`, and without a
 * fill mode any gap between the two lets the element revert to its natural height for a
 * frame — a full-height flash on the way out.
 */
[data-kida-collapse][data-state="closed"] {
  animation: kida-collapse-close var(--kida-collapse-duration, var(--kida-duration-md))
    var(--kida-collapse-ease, var(--kida-ease-in-out)) forwards;
}

/*
 * Mounted already-open: there is no previous state to animate from.
 * Declared last so it wins on order — both selectors have the same specificity, which is
 * why this needs no `!important`.
 */
[data-kida-collapse][data-skip-animation] {
  animation: none;
}

/* Presence checks computed animation styles before deciding whether to hold the node for an
   exit. A 1ms reduced-motion animation can finish before that listener is attached, leaving the
   closed node mounted forever. With no animation, presence removes it immediately. */
@media (prefers-reduced-motion: reduce) {
  [data-kida-collapse] {
    animation: none;
  }
}

/*
 * The root's vertical frame collapses with the content, because `height: 0` does not mean
 * "invisible": a root with a 1px border still renders a 2px box, and one with
 * `padding: 1rem` a 32px slab. Left in, that residue sits perfectly static at the end of
 * the close until presence unmounts — a hairline that hangs for a few frames and then
 * pops out.
 *
 * Both ends of every property are written out on purpose. An omitted end is supposed to
 * be filled in from the element's own value, and for `opacity` it is, but Chrome does not
 * synthesise one for border widths: a keyframe naming only `border-top-width: 0` leaves
 * the border sitting at its authored width for the whole animation. Hence the four
 * variables, which the component measures off the root and writes back. They are outputs,
 * not knobs — the `0px` fallbacks only stand in for the frame before the first
 * measurement lands, and a root with no border or padding animates 0 to 0 for free.
 *
 * Padding collapses cleanly, sub-pixel and all the way down. A border does not: Chrome
 * renders any width between 0 and 1px as a full hairline, so a 1px border reads as 1px
 * for the entire close and only disappears on the final frame. That is enough to keep the
 * last frame honest, but a bordered root still hits a 2px floor slightly before the
 * animation ends and holds it for a few frames. There is no CSS answer to that, so the
 * rule is: keep borders on the content, and let this root be the thing that clips it.
 */
@keyframes kida-collapse-open {
  from {
    height: 0;
    padding-top: 0;
    padding-bottom: 0;
    border-top-width: 0;
    border-bottom-width: 0;
  }
  to {
    height: var(--kida-collapse-height);
    padding-top: var(--kida-collapse-padding-top, 0px);
    padding-bottom: var(--kida-collapse-padding-bottom, 0px);
    border-top-width: var(--kida-collapse-border-top-width, 0px);
    border-bottom-width: var(--kida-collapse-border-bottom-width, 0px);
  }
}

@keyframes kida-collapse-close {
  from {
    height: var(--kida-collapse-height);
    padding-top: var(--kida-collapse-padding-top, 0px);
    padding-bottom: var(--kida-collapse-padding-bottom, 0px);
    border-top-width: var(--kida-collapse-border-top-width, 0px);
    border-bottom-width: var(--kida-collapse-border-bottom-width, 0px);
  }
  to {
    height: 0;
    padding-top: 0;
    padding-bottom: 0;
    border-top-width: 0;
    border-bottom-width: 0;
  }
}
src/lib/components/ui/kida/tokens.css
/*
 * Kida UI — motion tokens.
 * Plain CSS custom properties (ADR D7). No preprocessor, no Tailwind, no build step.
 */

:root {
  /* Durations */
  --kida-duration-xs: 100ms;
  --kida-duration-sm: 150ms;
  --kida-duration-md: 300ms;
  --kida-duration-lg: 500ms;
  --kida-duration-xl: 800ms;

  /* Easings */
  --kida-ease-out: cubic-bezier(0.16, 1, 0.3, 1);
  --kida-ease-in: cubic-bezier(0.7, 0, 0.84, 0);
  --kida-ease-in-out: cubic-bezier(0.65, 0, 0.35, 1);
  --kida-ease-spring: linear(0, 0.5, 0.9, 1.02, 1);

  /* Travel distances used by the enter/exit keyframes */
  --kida-distance-sm: 4px;
  --kida-distance-md: 8px;
  --kida-distance-lg: 16px;

  /* Stagger step between siblings */
  --kida-stagger: 60ms;
}

/*
 * The shared reduced-motion guard for CSS-driven animation in the library.
 * Durations collapse to ~0 by default. Components whose presence lifecycle cannot safely observe
 * a 1ms animation, such as Collapse, disable it explicitly and complete presence in their adapter.
 */
@media (prefers-reduced-motion: reduce) {
  :root {
    --kida-duration-xs: 1ms;
    --kida-duration-sm: 1ms;
    --kida-duration-md: 1ms;
    --kida-duration-lg: 1ms;
    --kida-duration-xl: 1ms;
    --kida-distance-sm: 0px;
    --kida-distance-md: 0px;
    --kida-distance-lg: 0px;
    --kida-stagger: 0ms;
  }
}
<script lang="ts">
import Collapse from '$lib/components/ui/kida/collapse.svelte'

let open = $state(false)
const panelId = $props.id()
</script>

<div>
  <button type="button" aria-expanded={open} aria-controls={open ? panelId : undefined} onclick={() => (open = !open)}>
    {open ? 'Hide details' : 'Show details'}
  </button>
  <Collapse id={panelId} {open}><div>Anything at all.</div></Collapse>
</div>

The copy-source command includes the required styles.

API

Props

Prop Type Default Description
open boolean — Whether the content is shown.
onExitComplete () => void — Called after the exit animation ends and the node is removed.
element HTMLDivElement | null null Use bind:element to read the collapsing root.
class string — Applied to the collapsing root.
style string — Applied to the collapsing root.

Native div attributes, class, style, and events apply to the collapsing root. The bound element becomes null after the exit animation finishes and the panel unmounts.

CSS custom properties

Property Default Description
--kida-collapse-duration --kida-duration-md Applies to both directions.
--kida-collapse-ease --kida-ease-out opening, --kida-ease-in-out closing Easing for each direction.

Customization

Set --kida-collapse-duration or --kida-collapse-ease on the Collapse root through a class or the style prop. Put visual borders, backgrounds, and padding on the inner content so the root can shrink cleanly to zero.

Accessibility and input behavior

Collapse preserves its children’s semantics and focus behavior while open. When reduced motion is requested, the transition is skipped while still unmounting the panel and calling onExitComplete.

Troubleshooting

Put borders and padding on the content inside Collapse, not on its root. The root needs to shrink cleanly to zero while it clips the panel.

Collapse uses @zag-js/presence and @zag-js/svelte, which the copy-source command installs.