---
title: Resizable for Astro
description: "Astro panels with pointer and keyboard size controls."
seo:
    title: Resizable for Astro | Shadcn & Tailwind CSS
related:
    - /components/scroll-area
    - /components/sidebar
sidebar:
    label: "Resizable"
---

```astro
---
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from "@/components/ui/resizable"
---

<ResizablePanelGroup class="h-48 w-full max-w-2xl rounded-lg border">
  <ResizablePanel defaultSize={50} minSize={20}>
    <div class="flex h-full flex-col items-center justify-center gap-2 p-6">
      <span class="font-semibold">Panel A</span>
      <span class="text-muted-foreground text-sm">
        Drag the handle to resize.
      </span>
    </div>
  </ResizablePanel>
  <ResizableHandle withHandle />
  <ResizablePanel defaultSize={50} minSize={20} class="bg-muted">
    <div class="flex h-full flex-col items-center justify-center gap-2 p-6">
      <span class="font-semibold">Panel B</span>
      <span class="text-muted-foreground text-sm">
        Arrow keys resize the focused handle.
      </span>
    </div>
  </ResizablePanel>
</ResizablePanelGroup>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/resizable
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

Install the component packages:

```sh
bun add @data-slot/core @data-slot/resizable
```

#### src/components/ui/resizable/index.ts

```ts
export { default as ResizableHandle } from './resizable-handle.astro'
export { default as ResizablePanel } from './resizable-panel.astro'
export { default as ResizablePanelGroup } from './resizable-panel-group.astro'
export type {
    ResizableHandleProps,
    ResizablePanelProps,
    ResizableProps,
} from './types.ts'
```

#### src/components/ui/resizable/resizable-handle.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import type { ResizableHandleProps } from "./types.ts"
import { cn } from "cn"

/**
 * Separator between two resizable panels.
 *
 * `@data-slot/resizable` sets `aria-orientation` on the handle after startup.
 * The parent `data-direction` classes paint the correct axis before that runs.
 * A horizontal group uses a vertical separator.
 * A vertical group uses a horizontal separator.
 */

type Props = HTMLAttributes<"div"> & ResizableHandleProps

const {
  class: className,
  withHandle = false,
  snapPoints,
  "aria-label": ariaLabel = "Resize panels",
  ...props
} = Astro.props
---

{/* The handle is really a panel separator */}
<div
  data-slot="resizable-handle"
  data-snap-points={snapPoints?.length ? snapPoints.join(",") : undefined}
  role="separator"
  tabindex="0"
  aria-label={ariaLabel}
  class={cn(
    "bg-border ring-offset-background relative flex w-px shrink-0 cursor-col-resize touch-none items-center justify-center select-none after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-hidden",
    "aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:cursor-row-resize aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:h-1 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2 [&[aria-orientation=horizontal]>div]:rotate-90",
    "[[data-direction=vertical]>&]:h-px [[data-direction=vertical]>&]:w-full [[data-direction=vertical]>&]:cursor-row-resize [[data-direction=vertical]>&]:after:left-0 [[data-direction=vertical]>&]:after:h-1 [[data-direction=vertical]>&]:after:w-full [[data-direction=vertical]>&]:after:translate-x-0 [[data-direction=vertical]>&]:after:-translate-y-1/2 [[data-direction=vertical]>&]:[&>div]:rotate-90",
    className,
  )}
  {...props}
>
  {/* Small handle in the center of the separator */}
  {withHandle && (
    <div class="bg-border z-10 flex h-6 w-1 shrink-0 rounded-lg" data-slot="resizable-handle-handle" />
  )}
  <slot />
</div>
```

#### src/components/ui/resizable/resizable-panel-group.astro

```astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"
import type { ResizableProps } from "./types.ts"

/**
 * Group of panels that share space.
 *
 * `@data-slot/resizable` binds `data-slot="resizable"`.
 * The public component name stays `ResizablePanelGroup`.
 */

type Props = HTMLAttributes<"div"> & ResizableProps

const {
  class: className,
  direction = "horizontal",
  keyboardResizeBy,
  ...props
} = Astro.props

/**
 * Keep a numeric 0 in the attribute.
 * Astro can omit a bare 0.
 */
const dataNumber = (value: number | undefined) =>
  value === undefined ? undefined : String(value)
---

<div
  data-slot="resizable"
  data-direction={direction}
  data-keyboard-resize-by={dataNumber(keyboardResizeBy)}
  class={cn(
    "flex h-full w-full min-h-0 min-w-0 overflow-hidden data-[direction=vertical]:flex-col",
    className,
  )}
  {...props}
>
  <slot />
</div>

<script>
  import { create } from "./snap-points.ts"
  // Destroy bindings before a view transition so the next page-load binds once.
  const controllers: ReturnType<typeof create> = []
  const initialize = () => controllers.push(...create())
  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  })
</script>
```

#### src/components/ui/resizable/resizable-panel.astro

```astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"
import type { ResizablePanelProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & ResizablePanelProps

const {
  class: className,
  defaultSize,
  minSize,
  maxSize,
  collapsible,
  collapsedSize,
  style,
  ...props
} = Astro.props

/**
 * Keep a numeric 0 in the attribute.
 * Astro can omit a bare 0.
 */
const dataNumber = (value: number | undefined) =>
  value === undefined ? undefined : String(value)

const layoutStyle = defaultSize === undefined ? "" : `flex-grow:${defaultSize}`
const userStyle = typeof style === "string" ? style : ""
const mergedStyle =
  [layoutStyle, userStyle].filter(Boolean).join(";") || undefined
---

<div
  data-slot="resizable-panel"
  data-default-size={dataNumber(defaultSize)}
  data-min-size={dataNumber(minSize)}
  data-max-size={dataNumber(maxSize)}
  data-collapsible={collapsible ? "" : undefined}
  data-collapsed-size={dataNumber(collapsedSize)}
  class={cn("min-h-0 min-w-0 flex-1 overflow-hidden", className)}
  style={mergedStyle}
  {...props}
>
  <slot />
</div>
```

#### src/components/ui/resizable/snap-points.ts

```ts
import {
    getDataBool,
    getParts,
    getRoots,
    hasRootBinding,
    on,
} from '@data-slot/core'
import { createResizable, type ResizableController } from '@data-slot/resizable'

/** Check the two panes beside the handle so a snap never moves another pane. */
function allows(panel: HTMLElement, size: number) {
    const { minSize = 0, maxSize = 100, collapsedSize = 0 } = panel.dataset
    return (
        (size >= Number(minSize) && size <= Number(maxSize)) ||
        (getDataBool(panel, 'collapsible') && size === Number(collapsedSize))
    )
}

function bindStops(
    root: HTMLElement,
    controller: ResizableController,
    handle: HTMLElement,
    index: number,
    panels: HTMLElement[],
) {
    const points = (handle.dataset.snapPoints ?? '')
        .split(',')
        .filter((point) => point.trim() !== '')
        .map(Number)
        .filter((point) => Number.isFinite(point) && point >= 0 && point <= 100)
        .sort((a, b) => a - b)
    if (!points.length) return []
    const before = panels[index]!
    const after = panels[index + 1]!
    const view = root.ownerDocument.defaultView!
    const available = () => {
        const sum = controller.getSize(index) + controller.getSize(index + 1)
        return points.filter(
            (point) =>
                allows(before, point) &&
                allows(after, Number((sum - point).toFixed(10))),
        )
    }

    // The primitive starts the drag at the handle. Finish a snap only on release.
    // Cancel, blur, a programmatic resize, and teardown discard the pending snap.
    let stopRelease: (() => void) | undefined
    function clearRelease() {
        stopRelease?.()
        stopRelease = undefined
    }
    function start(event: MouseEvent | TouchEvent) {
        if (handle.dataset.active !== 'pointer') return
        if (
            'touches' in event ? event.touches.length !== 1 : event.button !== 0
        )
            return
        clearRelease()
        const startSize = controller.getSize(index)
        const snap = () => {
            const size = controller.getSize(index)
            if (size === startSize) return
            const nearest = available().reduce<number | undefined>(
                (best, point) =>
                    best === undefined ||
                    Math.abs(size - point) < Math.abs(size - best)
                        ? point
                        : best,
                undefined,
            )
            if (nearest !== undefined) controller.resizePane(index, nearest)
        }
        if ('touches' in event) {
            const id = event.touches[0]?.identifier
            stopRelease = on(
                view,
                'touchend',
                (end) => {
                    if (
                        Array.from(end.changedTouches).some(
                            (touch) => touch.identifier === id,
                        )
                    )
                        snap()
                },
                { capture: true },
            )
        } else {
            stopRelease = on(view, 'mouseup', snap, { capture: true })
        }
    }
    function keydown(event: KeyboardEvent) {
        if (
            event.defaultPrevented ||
            event.shiftKey ||
            handle.dataset.disabled === 'true'
        )
            return
        const vertical = root.dataset.direction === 'vertical'
        const keys = vertical
            ? ['ArrowUp', 'ArrowDown']
            : ['ArrowLeft', 'ArrowRight']
        if (!keys.includes(event.key)) return
        const stops = available()
        if (!stops.length) return
        let forward = event.key === keys[1]
        if (!vertical && root.ownerDocument.dir === 'rtl') forward = !forward
        const size = controller.getSize(index)
        const next = forward
            ? stops.find((point) => point > size)
            : stops.reverse().find((point) => point < size)
        event.preventDefault()
        if (next !== undefined) controller.resizePane(index, next)
    }
    return [
        on(handle, 'mousedown', start),
        on(handle, 'touchstart', start),
        on(handle, 'keydown', keydown, { capture: true }),
        on(root, 'resizable:dragging', (event) => {
            if (
                event.target === root &&
                !(event as CustomEvent).detail.dragging
            )
                clearRelease()
        }),
        clearRelease,
    ]
}

/** Bind each new group once, with its own handles and native resize controller. */
export function create(scope: ParentNode = document) {
    return getRoots<HTMLElement>(scope, 'resizable')
        .filter((root) => !hasRootBinding(root, '@data-slot/resizable'))
        .map((root) => {
            const controller = createResizable(root)
            const panels = getParts<HTMLElement>(root, 'resizable-panel')
            const cleanups = getParts<HTMLElement>(
                root,
                'resizable-handle',
            ).flatMap((handle, index) =>
                bindStops(root, controller, handle, index, panels),
            )
            return {
                destroy() {
                    cleanups.splice(0).forEach((cleanup) => cleanup())
                    controller.destroy()
                },
            }
        })
}
```

#### src/components/ui/resizable/types.ts

```ts
import type { ResizableDirection } from '@data-slot/resizable'

/** Configuration for a group of resizable panels. */
export type ResizableProps = {
    /**
     * Layout axis for the panels.
     * `horizontal` places panels side by side.
     * `vertical` stacks the panels.
     * @default "horizontal"
     */
    direction?: ResizableDirection
    /**
     * Percent added or removed for each arrow key press.
     * Shift with an arrow key moves to the limit.
     * @default 10
     */
    keyboardResizeBy?: number
}

export type ResizablePanelProps = {
    /**
     * Initial size as a percentage of the group.
     * Panels without a size share the remaining space.
     */
    defaultSize?: number
    /**
     * Minimum size as a percentage.
     * @default 0
     */
    minSize?: number
    /**
     * Maximum size as a percentage.
     * @default 100
     */
    maxSize?: number
    /**
     * Allow this panel to collapse past `minSize`.
     * Press Enter on the preceding handle to collapse and expand it.
     * @default false
     */
    collapsible?: boolean
    /**
     * Size as a percentage when the panel is collapsed.
     * This value must not exceed `minSize`.
     * @default 0
     */
    collapsedSize?: number
}

export type ResizableHandleProps = {
    /**
     * Optional sizes for the panel before this handle, as percentages of the group.
     * Release a drag to select the nearest available size. Arrow keys select
     * the previous or next size. Both adjacent panels must allow that size.
     */
    snapPoints?: readonly number[]
    /**
     * Show a grip in the center of the handle.
     * @default false
     */
    withHandle?: boolean
}
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Usage

```astro
---
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from "@/components/ui/resizable"
---
```

```astro
<ResizablePanelGroup class="h-48 w-full rounded-lg border">
  <ResizablePanel defaultSize={50} minSize={20}>
    <div class="flex h-full items-center justify-center p-6">One</div>
  </ResizablePanel>
  <ResizableHandle />
  <ResizablePanel defaultSize={50} minSize={20}>
    <div class="flex h-full items-center justify-center p-6">Two</div>
  </ResizablePanel>
</ResizablePanelGroup>
```

## Composition

Place one `ResizableHandle` between each pair of panels. Sizes are percentages of the group. Give the group a height.

```text
ResizablePanelGroup
├── ResizablePanel
├── ResizableHandle
└── ResizablePanel
```

## Examples

### Vertical

Set `direction="vertical"` to stack the panels. The handle moves up and down.

```astro
---
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from "@/components/ui/resizable"
---

<ResizablePanelGroup
  direction="vertical"
  class="h-64 w-full max-w-md rounded-lg border"
>
  <ResizablePanel defaultSize={40} minSize={20}>
    <div class="flex h-full flex-col items-center justify-center gap-2 p-6">
      <span class="font-semibold">Panel A</span>
      <span class="text-muted-foreground text-sm">
        Drag the handle to resize.
      </span>
    </div>
  </ResizablePanel>
  <ResizableHandle withHandle />
  <ResizablePanel defaultSize={60} minSize={20} class="bg-muted">
    <div class="flex h-full flex-col items-center justify-center gap-2 p-6">
      <span class="font-semibold">Panel B</span>
      <span class="text-muted-foreground text-sm">
        Up and down arrow keys resize this group.
      </span>
    </div>
  </ResizablePanel>
</ResizablePanelGroup>
```

### Custom handle

Add a custom handle by passing a direct child to `ResizableHandle`.

```astro
---
import GripVerticalIcon from "@lucide/astro/icons/grip-vertical"
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from "@/components/ui/resizable"
---

<ResizablePanelGroup class="h-48 w-full max-w-2xl rounded-lg border">
  <ResizablePanel defaultSize={50} minSize={20}>
    <div class="flex h-full flex-col items-center justify-center gap-2 p-6">
      <span class="font-semibold">Panel A</span>
      <span class="text-muted-foreground text-sm">
        Drag the custom handle to resize.
      </span>
    </div>
  </ResizablePanel>
  <ResizableHandle>
    <GripVerticalIcon class="h-6 w-3 bg-border z-10 flex shrink-0 rounded-lg text-muted-foreground/72" />
  </ResizableHandle>
  <ResizablePanel defaultSize={50} minSize={20} class="bg-muted">
    <div class="flex h-full flex-col items-center justify-center gap-2 p-6">
      <span class="font-semibold">Panel B</span>
      <span class="text-muted-foreground text-sm">
        Arrow keys resize the focused panel.
      </span>
    </div>
  </ResizablePanel>
</ResizablePanelGroup>
```

### Nested groups

A panel can contain another group. Use `withHandle` to show a grip on the separator.

```astro
---
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from "@/components/ui/resizable"
---

<ResizablePanelGroup class="h-64 w-full max-w-2xl rounded-lg border">
  <ResizablePanel defaultSize={50} minSize={20}>
    <div class="flex h-full items-center justify-center p-6">
      <span class="font-semibold">One</span>
    </div>
  </ResizablePanel>
  <ResizableHandle withHandle />
  <ResizablePanel defaultSize={50} minSize={20}>
    <ResizablePanelGroup direction="vertical" class="h-full">
      <ResizablePanel defaultSize={30} minSize={15}>
        <div class="flex h-full items-center justify-center p-6">
          <span class="font-semibold">Two</span>
        </div>
      </ResizablePanel>
      <ResizableHandle withHandle />
      <ResizablePanel defaultSize={70} minSize={15} class="bg-muted">
        <div class="flex h-full items-center justify-center p-6">
          <span class="font-semibold">Three</span>
        </div>
      </ResizablePanel>
    </ResizablePanelGroup>
  </ResizablePanel>
</ResizablePanelGroup>
```

### Collapsible panel

Set `collapsible` on a panel to let it collapse past `minSize`. Focus the handle and press Enter to collapse and expand that panel. Arrow keys resize by 10 percent. Home and End move to the limits.

```astro
---
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from "@/components/ui/resizable"
---

<ResizablePanelGroup class="h-48 w-full max-w-2xl rounded-lg border">
  <ResizablePanel
    defaultSize={25}
    minSize={15}
    collapsible
    collapsedSize={0}
    class="bg-muted"
  >
    <div class="flex h-full items-center justify-center p-4">
      <span class="text-sm font-semibold">Sidebar</span>
    </div>
  </ResizablePanel>
  <ResizableHandle withHandle aria-label="Resize sidebar" />
  <ResizablePanel defaultSize={75} minSize={30}>
    <div class="flex h-full flex-col items-center justify-center gap-2 p-6">
      <span class="font-semibold">Content</span>
      <span class="text-muted-foreground text-center text-sm">
        Focus the handle and press Enter to collapse the sidebar.
      </span>
    </div>
  </ResizablePanel>
</ResizablePanelGroup>
```

### Snap points

Set `snapPoints` on a handle to give the panel before it a set of widths or heights. Each number is a percentage of the whole group. Release a drag to select the nearest size that both adjacent panels allow. A tie selects the smaller size. Use the arrow keys to move between stops. Home and End still move to the panel limits.

```astro
---
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from "@/components/ui/resizable"
---

<ResizablePanelGroup class="h-48 w-full max-w-2xl rounded-lg border">
  <ResizablePanel defaultSize={25} minSize={20} class="bg-muted p-4">
    Files
  </ResizablePanel>
  <ResizableHandle
    withHandle
    snapPoints={[25, 50, 75]}
    aria-label="Resize file list"
  />
  <ResizablePanel defaultSize={75} minSize={20} class="p-4">
    <p class="font-semibold">Editor</p>
    <p class="mt-2 text-sm text-muted-foreground">
      Drag the divider or use the arrow keys to set the file list to 25%, 50%,
      or 75%.
    </p>
  </ResizablePanel>
</ResizablePanelGroup>
```

## API Reference

`ResizablePanelGroup`, `ResizablePanel`, and `ResizableHandle` accept native div attributes.

### ResizablePanelProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/resizable/types.ts"
    name="ResizablePanelProps"
/>

### ResizableProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/resizable/types.ts"
    name="ResizableProps"
/>

### ResizableHandleProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/resizable/types.ts"
    name="ResizableHandleProps"
/>

### Events

Dispatch these events on the resizable group root. The root emits the outbound events. The component does not store the layout.

#### Outbound events

| Event                | Detail                  |
| -------------------- | ----------------------- |
| `resizable:change`   | `{ layout: number[] }`  |
| `resizable:dragging` | `{ dragging: boolean }` |

#### Inbound events

| Event           | Detail                 |
| --------------- | ---------------------- |
| `resizable:set` | `{ layout: number[] }` |

See the [data-slot docs](https://data-slot.com/components/resizable/) for keyboard behavior and the controller API.

Read the [installed source](/ui/r/resizable.json) for the component source.

## When to use Resizable

Compose panels and resize handles inside a ResizablePanelGroup. Choose an orientation and useful size bounds so neither panel becomes unusable. Keep the panel content independent of its starting size.

## Keyboard and behavior

The existing data-slot controller handles pointer and keyboard resizing. Give each handle a useful label and test its arrow-key behavior. A panel that contains a form must still expose all controls at its minimum size.

## Theme and layout

The handle uses shared border and focus colors. Check content overflow after a resize and at narrow viewport widths. Some layouts are clearer when panels stack instead of remaining resizable on a phone.
