About
An aspect ratio picker for image and video models: ratios with shape glyphs, ones the model does not support turned off, a custom size snapped to the model grid with a lock, and a compact popover form.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Aspect Ratio Picker to your project and fits it to your theme.
Code
How Aspect Ratio Picker is used: the demo's code. The component's own source comes with a free account.
Usage.tsx
"use client"
import * as React from "react"
import { AspectRatioPicker, parseAspectRatio } from "@/components/ui/aspect-ratio-picker"
const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches
/** Pixel size near one megapixel, in multiples of 64, the way most image models want it. */
function sizeFor(value: string) {
const parsed = parseAspectRatio(value)
if (!parsed) return { width: 1024, height: 1024 }
if (parsed.width > 64 || parsed.height > 64) return parsed
const area = 1024 * 1024
const width = Math.round(Math.sqrt(area * parsed.ratio) / 64) * 64
return { width, height: Math.round(width / parsed.ratio / 64) * 64 }
}
/** The segmented row, with a frame that takes the shape you pick. */
function AspectRatioPickerDemo() {
const [value, setValue] = React.useState("3:2")
const { width, height } = sizeFor(value)
const ratio = parseAspectRatio(value)?.ratio ?? width / height
return (
<div className="flex w-full max-w-xl flex-col items-start gap-5">
<AspectRatioPicker value={value} onValueChange={setValue} />
<div className="grid h-56 w-full place-items-center">
<div
className="bg-(color:--chatcn-fill) rounded-(--chatcn-radius-md) relative grid max-h-56 max-w-full place-items-center shadow-[inset_0_0_0_1px_var(--chatcn-alpha-400)]"
style={{
aspectRatio: ratio,
height: ratio >= 1 ? undefined : "100%",
width: ratio >= 1 ? "min(100%, 22rem)" : undefined,
}}
>
<span className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) tabular-nums">
{width} × {height}
</span>
</div>
</div>
</div>
)
}
function Labeled({ label, children }: { label: string; children: React.ReactNode }) {
return (
<section className="flex min-w-0 flex-col gap-2.5">
<h3 className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) font-medium">{label}</h3>
{children}
</section>
)
}
/** Options a model does not support, custom size and fully disabled. */
function AspectRatioPickerStates() {
return (
<div className="flex w-full max-w-2xl flex-col gap-8">
<Labeled label="Model supports four ratios">
<AspectRatioPicker
defaultValue="1:1"
allowCustom={false}
options={[
"1:1",
{ value: "4:5", disabled: true },
"3:2",
{ value: "4:3", disabled: true },
"16:9",
"9:16",
{ value: "21:9", disabled: true },
]}
/>
</Labeled>
<Labeled label="Custom size, snapped to multiples of 64">
<AspectRatioPicker defaultValue="1920:1088" step={64} />
</Labeled>
<Labeled label="Disabled while generating">
<div className="flex flex-wrap items-center gap-4">
<AspectRatioPicker defaultValue="16:9" disabled />
<AspectRatioPicker layout="popover" defaultValue="16:9" disabled />
</div>
</Labeled>
</div>
)
}
const VIEWS = [AspectRatioPickerDemo, AspectRatioPickerStates]
const VIEW_MS = 2200
const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"
/**
* 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
* phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
* render white on dark pages. FitFrame fills the frame exactly instead.
*
* - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
* - "crop": the content stays at full size from the top and fades out at the bottom. For text
* that streams in, where a changing scale would make the page breathe.
*
* `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
* to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
* shrinks evenly on both sides.
*
* Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
* shorter than `hideBelow`, so a profile card shows the visual alone.
*/
function FitFrame({
children,
mode = "scale",
hideBelow = 360,
minWidth,
}: {
children: React.ReactNode
mode?: "scale" | "crop"
hideBelow?: number
minWidth?: string
}) {
const content = React.useRef<HTMLDivElement>(null)
const [cropped, setCropped] = React.useState(false)
React.useLayoutEffect(() => {
const el = content.current
if (!el) return
const measure = () => {
const vw = window.innerWidth
const vh = window.innerHeight
el.toggleAttribute("data-fit-small", vh < hideBelow)
// Layout sizes ignore the transform, so measuring never feeds back.
const w = Math.max(el.offsetWidth, el.scrollWidth)
const h = Math.max(el.offsetHeight, el.scrollHeight)
const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
el.style.transform = scale < 1 ? `scale(${scale})` : ""
setCropped(mode === "crop" && h > vh + 1)
}
measure()
const observer = new ResizeObserver(measure)
observer.observe(el)
// Content that changes inside a fixed width box (a headline that cycles words) never resizes
// the box itself, so changes below it measure again on the next frame.
let frame = 0
const mutations = new MutationObserver(() => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(measure)
})
mutations.observe(el, { subtree: true, childList: true, characterData: true })
window.addEventListener("resize", measure)
return () => {
observer.disconnect()
mutations.disconnect()
cancelAnimationFrame(frame)
window.removeEventListener("resize", measure)
}
}, [mode, hideBelow])
const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
return (
<div
className="flex w-full justify-center overflow-hidden"
style={{
height: "100dvh",
alignItems: mode === "crop" ? "flex-start" : "center",
maskImage: cropped ? fade : undefined,
WebkitMaskImage: cropped ? fade : undefined,
}}
>
<style>{FIT_CSS}</style>
<div
ref={content}
className="w-full shrink-0"
style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
>
{children}
</div>
</div>
)
}
/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
return (
<p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
{children}{" "}
<a
href={`https://chatcn.dev/docs/components/${slug}`}
target="_blank"
rel="noopener"
className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
>
chatcn.dev
</a>
</p>
)
}
/**
* The kit's own examples, crossfading every couple of seconds. They share one grid cell, so the
* frame keeps the size of the larger one and never rescales.
*/
export default function AspectRatioPickerPreview() {
const [view, setView] = React.useState(0)
React.useEffect(() => {
if (reducedMotion()) return
const id = window.setInterval(() => setView((v) => (v + 1) % VIEWS.length), VIEW_MS)
return () => window.clearInterval(id)
}, [])
return (
<FitFrame minWidth="36rem">
<div className="flex w-full flex-col items-center justify-center gap-4 p-6">
<div className="grid w-full max-w-2xl">
{VIEWS.map((View, i) => (
<div
// biome-ignore lint/suspicious/noArrayIndexKey: a fixed list.
key={i}
aria-hidden={i !== view}
inert={i !== view}
className="col-start-1 row-start-1 flex items-center justify-center transition-opacity duration-300"
style={{ opacity: i === view ? 1 : 0 }}
>
<View />
</div>
))}
</div>
<MoreOn slug="aspect-ratio-picker">Pick an aspect ratio for an image or video. On</MoreOn>
</div>
</FitFrame>
)
}
















