Card
A container with header, content, and footer sections. Includes dashboard and metric card variants.
Installation
npx shadcn@latest add https://ui.mattdowney.com/r/card.jsonUsage
import {
Card, CardMedia, CardHeader, CardTitle, CardDescription, CardAction,
CardContent, CardFooter, CardRows, CardRow, CardTableHeader,
CardTableBody, DashboardCardHeader, MetricCardValue,
} from "@/components/ui/card"Examples
Default
Header, content, and footer are each optional. This one skips CardContent and lets the description carry the body, which is the shape a short confirmation card wants.
With Header Border
Add border-b to CardHeader to separate the header from content.
Choose which notifications you’d like to receive and how they’re delivered.
With Footer Border
Add border-t to CardFooter to close the card off with a divider. It supplies its own 20px above the actions as soon as it is bordered, matching the 20px already below them, so there is no pt-* to remember.
With Form
A form inside a card: field between the fields, and Field owns the label-to-control gap. No top-gap override: CardContent sees the fields and opens to 16px under a borderless header, where prose hugs it at 8px.
With Action
CardAction places a control in the top-right of the header. The body is CardRows + CardRow rather than a hand-rolled stack: a member list is a row list, so each row owns its padding and hairline and there is no inter-row gap to guess.
Jane Doe
jane@example.com
Alex Smith
alex@example.com
With Rows
CardLinkRow is a row in a card that links somewhere: a label, an optional icon and line under it, and a chevron. Use CardRow for rows that only display.
Muted Footer
CardFooter tone="muted" is the same rule-and-fill band TableFooter ships, for a buy row or totals row that should pair with a table beside it. CardDescription size="lg" steps the description to 16px where it carries the card's message.
Clickable Rows
Pass render to CardRow and the whole row becomes that element, with a hover fill and a focus ring. layout="block" stacks text in a column. Use CardLinkRow instead when a row wants a chevron or a count.
Flush Rows
inset="flush" drops the side padding for a row list inside CardContent, which already pads. The first row loses its top padding and the last its bottom, so the list ends on the card's own padding. Leave it off for rows that sit directly in the card.
Compact Header
DashboardCardHeader + MetricCardValue for data display cards.
Header Action Alignment
Action seating, default flush. A Badge, count, or caption puts its own edge on the 16px inset, level with the title. An icon Button or Kebab carries ~6px of hit-area chrome past its glyph, so it needs actionInset="icon" to seat the glyph there; using it on a bare Badge pulls the count 6px too tight.
Table Header
CardTableHeader adds column labels that align with grid rows below.
Expandable
Reveal detail rows with a smooth disclosure. The summary stays put and the toggle lives in the header (neither moves), while the rows expand via Collapsible - a measured height animation that eases open and closed. The card's height just follows the Collapsible, so there's no snap or layout shift.
Tabbed Filter
A card whose list is filtered by tabs. Pill tabs stay out of DashboardCardHeader: the framed track fills its 48px band. Give them their own region below, closed off from the list by a border-t. For tabs in the header itself, use Tabs variant="line".
Dotgrid
Set variant="dotgrid" to fill the card with a faint dot-grid canvas. The dots paint behind the content, so children sit on top of the staging surface. Used for positioning and placement demos.
Content sits on the canvas
Featured
featured rings the card in the accent colour, to mark the recommended plan in a row of them. It composes with variant, so it is a boolean, not a variant value.
Unlimited projects and priority support.
Muted
variant="muted" swaps the ring for a quiet muted fill: no edge, no shadow, same radius, padding and parts. For a grid that groups content without raising it. Keep it to plain content, since a muted band inside it does not show.
Sent to 1,240 people last week.
With Media
CardMedia puts an image flush at the top, clipped to the card's corners, with the copy below. For a card that leads with a picture but keeps its edge.

API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| variantCard | "default" | "dotgrid" | "muted" | "default" | Visual treatment. dotgrid fills the card with a faint dot-grid canvas that paints behind the content, a staging surface for positioning and placement demos. muted is a quiet bg-muted fill with no ring or shadow, for a grid that groups content without raising it; it needs no perimeter room. |
| featuredCard | boolean | false | Rings the card in the accent colour to mark the recommended one in a set, such as the plan to pick. Independent of variant. |
| sizeCardDescription | "default" | "lg" | "default" | default is 14px, a supporting line. lg is 16px, for a card whose description is its message and should read at the page description's size rather than as fine print. |
| toneCardFooter | "default" | "muted" | "default" | muted paints the footer as a band: a rule above and the muted fill, the same band TableFooter ships. Works on a card in both modes, since the muted fill sits one step off the card colour in light and dark. |
| layoutCardRow | "row" | "stack" | "row" | row lays the children on one line, vertically centred. block stacks them in a column that fills the width, for a row of text and controls. |
| insetCardRow | "default" | "flush" | "default" | default pads 16px each side, for rows sitting directly in the card. flush drops the side padding for a list inside CardContent; the first row also loses its top padding and the last its bottom. |
| renderCardRow | React.ReactElement | None | Makes the whole row one link or button: pass the element (<a href />, <Link href />, <button type="button" />) and the row's children go inside it. Adds a hover fill, a focus ring and a pointer cursor, and hides the rules around the hovered row. For a chevron, a count and a description line use CardLinkRow. |
| renderCardLink | React.ReactElement | None | Put CardLink in CardTitle to make the whole card one link: it covers the card, draws the focus ring inside the corners, and adds no hover fill. Pass render={<Link href="..." />} for a router link, or href for a plain <a>. A CardAction in the same card stays clickable above the link, and CardMedia lets clicks through, with no extra classes. |
| aspectCardMedia | "landscape" | "wide" | "square" | "landscape" | The image's shape: 3:2, 16:9 or 1:1. Reserved before the image loads. A plain <img> is stretched to cover. |
| animateHeightCard | boolean | false | Smoothly animates the card's own height when its content size changes. Opt-in; leave off when a child already animates its own height (e.g. an inner Collapsible). |
| title*DashboardCardHeader | string | None | Header label, truncated when it overflows. |
| actionDashboardCardHeader | React.ReactNode | None | Optional control rendered on the right side of the header. |
| actionInsetDashboardCardHeader | "icon" | "flush" | "flush" | How the action seats against the right edge. flush (default) puts the action's own box edge on the content inset, so a Badge, count, or caption aligns with the title. icon outdents 6px for an action whose box extends past what you see (an icon Button or Kebab's transparent hit area, a ghost text button's padding), seating the glyph on the inset instead. The default is flush because a badge dropped in unadorned must look right with no flag; the button case declares its own chrome compensation. |
| linkDashboardCardHeader | { label: string; onClick: () => void } | None | Subtle text-button link on the right of the header; ignored when action is set. |
| insetDashboardCardHeader | "default" | "loose" | "default" | Side padding, which must match the body's below it. default (16px) is the row tier and fits most cards. loose (24px) is the prose tier, for a card whose body is paragraphs rather than rows, where 16px reads thin once the card is wide. Set the body to match in the same edit: the header and the content share one left edge, so moving either alone puts the title 8px inboard of every line beneath it. |
| value*MetricCardValue | React.ReactNode | None | The large metric value. |
| goal*MetricCardValue | React.ReactNode | None | Goal line rendered under the value. |
| unitMetricCardValue | string | None | Unit suffix appended to the goal line. |
| deltaMetricCardValue | { value: number; label?: string } | None | Progress remainder line: positive values render label (default {value} to go), zero or below renders Goal reached!. |
| childrenMetricCardValue | React.ReactNode | None | Optional inline controls rendered beside the value (e.g. +/- buttons). |
| columns*CardTableHeader | string[] | None | Column labels for the header row. |
| gridClassName*CardTableHeader | string | None | Grid classes matching the body rows, e.g. grid-cols-[10rem_1fr_5rem]. |
variantCard"default" | "dotgrid" | "muted" = "default"Visual treatment. dotgrid fills the card with a faint dot-grid canvas that paints behind the content, a staging surface for positioning and placement demos. muted is a quiet bg-muted fill with no ring or shadow, for a grid that groups content without raising it; it needs no perimeter room. |
featuredCardboolean = falseRings the card in the accent colour to mark the recommended one in a set, such as the plan to pick. Independent of variant. |
sizeCardDescription"default" | "lg" = "default"default is 14px, a supporting line. lg is 16px, for a card whose description is its message and should read at the page description's size rather than as fine print. |
toneCardFooter"default" | "muted" = "default"muted paints the footer as a band: a rule above and the muted fill, the same band TableFooter ships. Works on a card in both modes, since the muted fill sits one step off the card colour in light and dark. |
layoutCardRow"row" | "stack" = "row"row lays the children on one line, vertically centred. block stacks them in a column that fills the width, for a row of text and controls. |
insetCardRow"default" | "flush" = "default"default pads 16px each side, for rows sitting directly in the card. flush drops the side padding for a list inside CardContent; the first row also loses its top padding and the last its bottom. |
renderCardRowReact.ReactElementMakes the whole row one link or button: pass the element (<a href />, <Link href />, <button type="button" />) and the row's children go inside it. Adds a hover fill, a focus ring and a pointer cursor, and hides the rules around the hovered row. For a chevron, a count and a description line use CardLinkRow. |
renderCardLinkReact.ReactElementPut CardLink in CardTitle to make the whole card one link: it covers the card, draws the focus ring inside the corners, and adds no hover fill. Pass render={<Link href="..." />} for a router link, or href for a plain <a>. A CardAction in the same card stays clickable above the link, and CardMedia lets clicks through, with no extra classes. |
aspectCardMedia"landscape" | "wide" | "square" = "landscape"The image's shape: 3:2, 16:9 or 1:1. Reserved before the image loads. A plain <img> is stretched to cover. |
| animateHeightCardboolean = falseSmoothly animates the card's own height when its content size changes. Opt-in; leave off when a child already animates its own height (e.g. an inner Collapsible). |
| title*DashboardCardHeaderstringHeader label, truncated when it overflows. |
| actionDashboardCardHeaderReact.ReactNodeOptional control rendered on the right side of the header. |
actionInsetDashboardCardHeader"icon" | "flush" = "flush"How the action seats against the right edge. flush (default) puts the action's own box edge on the content inset, so a Badge, count, or caption aligns with the title. icon outdents 6px for an action whose box extends past what you see (an icon Button or Kebab's transparent hit area, a ghost text button's padding), seating the glyph on the inset instead. The default is flush because a badge dropped in unadorned must look right with no flag; the button case declares its own chrome compensation. |
linkDashboardCardHeader{ label: string; onClick: () => void }Subtle text-button link on the right of the header; ignored when action is set. |
insetDashboardCardHeader"default" | "loose" = "default"Side padding, which must match the body's below it. default (16px) is the row tier and fits most cards. loose (24px) is the prose tier, for a card whose body is paragraphs rather than rows, where 16px reads thin once the card is wide. Set the body to match in the same edit: the header and the content share one left edge, so moving either alone puts the title 8px inboard of every line beneath it. |
| value*MetricCardValueReact.ReactNodeThe large metric value. |
| goal*MetricCardValueReact.ReactNodeGoal line rendered under the value. |
| unitMetricCardValuestringUnit suffix appended to the goal line. |
deltaMetricCardValue{ value: number; label?: string }Progress remainder line: positive values render label (default {value} to go), zero or below renders Goal reached!. |
| childrenMetricCardValueReact.ReactNodeOptional inline controls rendered beside the value (e.g. +/- buttons). |
| columns*CardTableHeaderstring[]Column labels for the header row. |
gridClassName*CardTableHeaderstringGrid classes matching the body rows, e.g. grid-cols-[10rem_1fr_5rem]. |
import * as React from "react"
import { cn } from "@/registry/lib/utils"
import { AnimatedCardShell } from "@/registry/ui/card-animate-height"
import { cardDotgridClass } from "@/registry/ui/card-classes"
// The edge is `shadow-ring-md` (an OUTER box-shadow hairline), not a border.
// An overflow-hidden or flush-edge ancestor will clip it: give a Card perimeter
// room, and counter with negative margin if you need flush alignment. A `muted`
// card has no ring and no shadow, so it paints nothing outside its box and
// needs no perimeter room.
//
// The card clips its children to its corners with `overflow-clip`, NOT
// `overflow-hidden`. Hidden makes the card a scroll container, and a sticky
// child (a pinned toolbar, a sidebar) sticks to the nearest scroll container,
// so inside a hidden card it never sticks. The workaround that invites is
// `overflow-visible`, and then a square header band (bg-muted) pokes past the
// rounded corner and paints over the ring there. Clip trims the same corners
// and leaves sticky to the page.
// A card holding a CardLink is the positioning box its stretched link fills.
const cardBase =
"text-foreground flex flex-col rounded-lg overflow-clip has-[[data-slot=card-link]]:relative"
// The surface each variant paints. `default` and `dotgrid` are the card tier:
// the card fill with the ring as the edge. `muted` is a quiet fill with no ring,
// border or shadow, for a set of cards that should read as grouped content
// rather than raised boxes (a testimonial grid). `bg-muted` sits one step off
// the page in light (1.05:1, the same step the card fill takes) and a little
// firmer in dark (1.15:1), where a dark surface needs a larger lightness step
// to read at all; on a card-coloured band it is 1.09:1 in both modes, so the
// set still reads there. With no ring, Windows high contrast (which drops the
// fill) would leave nothing, so it draws the same 1px inset outline the token
// file gives a ring.
const CARD_SURFACE = {
default: "bg-card shadow-ring-md",
dotgrid: cn("bg-card shadow-ring-md", cardDotgridClass),
muted: "bg-muted forced-colors:outline forced-colors:-outline-offset-1",
} as const
// @use-when a bounded surface (edge, radius) sitting on the page, holding one
// group of related content: a form panel, a summary, a settings group, or a
// linked card led by an image inside its edge (CardMedia); `variant="muted"`
// for a quiet ringless fill in a grid that groups content without raising it.
// Not Section, a full-width band with no box; not Dialog, which covers the page.
function Card({
variant = "default",
featured = false,
animateHeight,
className,
children,
...props
}: React.ComponentProps<"div"> & {
/** Visual treatment. `dotgrid` fills the card with a faint dot-grid canvas -
* a staging surface for positioning/placement demos. `muted` is a quiet
* muted fill with no ring or shadow, for a grid of cards that groups
* content without raising it (testimonials). Same radius, padding and parts
* as the default. A band that paints `bg-muted` inside it (CardFooter
* `tone="muted"`, CardTableHeader, DashboardCardHeader) does not show on
* it: keep a muted card to plain content. */
variant?: keyof typeof CARD_SURFACE
/** Marks the card as the recommended one in a set (the plan to pick). Adds a
* 2px accent ring over the card's hairline. A boolean rather than a
* `variant` value, because it is a second axis: a dotgrid card can be
* featured too, and a variant could only be one of the two. */
featured?: boolean
/** Smoothly animate the card's own height when its content size changes
* (a child grows/shrinks/swaps). Opt-in - leave off when a child already
* animates its own height (e.g. an inner Collapsible). Pulls in a small
* client shell only when enabled; the default Card stays server-rendered. */
animateHeight?: boolean
}) {
// Dots paint as the root's background-image, so they always sit behind the
// card's content (no overlay layer that could cover controls).
const classes = cn(
cardBase,
CARD_SURFACE[variant],
// The featured ring is a box-shadow, so Windows high contrast removes it;
// a 2px outline stands in (`!` beats the token file's 1px outline on
// `shadow-ring-md`, which is unlayered).
featured && "ring-2 ring-accent forced-colors:outline-2!",
className
)
if (animateHeight) {
return <AnimatedCardShell className={classes} {...props}>{children}</AnimatedCardShell>
}
return (
<div data-slot="card" className={classes} {...props}>
{children}
</div>
)
}
const CARD_MEDIA_ASPECT = {
landscape: "aspect-[3/2]",
wide: "aspect-video",
square: "aspect-square",
} as const
/** An image flush at the card's top. The card's own `overflow-clip` clips it
* to the corners, so the image needs no radius of its own, and a hairline
* under it separates the picture from the copy. The shape is reserved before
* the image loads, so nothing below it moves. Put it first, then a
* CardHeader: the header's own top padding is the gap. */
function CardMedia({
aspect = "landscape",
className,
...props
}: React.ComponentProps<"div"> & {
/** 3:2, 16:9 or 1:1. */
aspect?: keyof typeof CARD_MEDIA_ASPECT
}) {
return (
<div
data-slot="card-media"
className={cn(
"relative shrink-0 overflow-hidden border-b border-border bg-muted *:absolute *:inset-0 *:size-full *:object-cover",
// In a card a CardLink covers, the picture is part of the link: it
// never catches a click, whatever is layered inside it.
"[[data-slot=card]:has([data-slot=card-link])_&]:pointer-events-none",
CARD_MEDIA_ASPECT[aspect],
className
)}
{...props}
/>
)
}
function CardHeader({ className, style, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
// No pb by default: whatever follows owns the gap, which is why
// CardContent carries its own pt. A FOOTER cannot, though. Its pt-5
// sits below its own border-t, and the missing space is above that
// line, on the header's side, so a header followed straight by a
// bordered footer put the rule on the description's descenders. The
// header has to supply it, and it does so whether or not the footer is
// bordered: a borderless footer was told to borrow 20px from the
// content above it, and with no content above it there was none.
// A header that is the whole card (`last:`) has nothing after it to
// own the gap, so it pads its own bottom to match its top.
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start px-4 pt-5 last:pb-5 [&:has(+[data-slot=card-footer])]:pb-5 [&:has(+[data-slot=card-rows])]:pb-5 has-data-[slot=card-action]:grid-cols-[1fr_auto]",
className
)}
// Title-to-description gap is the pair rung, set via inline style: a
// gap-* class would freeze the compiled length (see stack.tsx /
// page-header.tsx for the same move).
style={{ ...style, gap: "var(--spacing-rhythm-pair)" }}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
// leading-tight, not leading-none: a title that wraps to two lines would
// collide ascenders into descenders at 1.0. Not snug either: the title
// sits on the 4px pair rung over its description, and snug's extra
// half-leading opened that pair. The description keeps its own reading
// leading because it wraps.
// text-pretty, NOT text-balance. See dialog.tsx for the full reason; the
// short version is that balance narrows the block to its tightest fit, so
// a wrapped title stops short of the card's right edge while the
// description under it runs to the edge, and two left-aligned blocks with
// different right edges read as a mistake. pretty keeps the full width
// and only pulls a word down to kill an orphan, which was the actual
// defect balance was hired to fix.
className={cn("leading-tight font-semibold text-pretty", className)}
{...props}
/>
)
}
function CardDescription({
size = "default",
className,
...props
}: React.ComponentProps<"div"> & {
/** `default` is 14px, a supporting line. `lg` is 16px, for a card whose
* description IS its message and should read at the page description's
* size rather than as fine print. */
size?: "default" | "lg"
}) {
return (
<div
data-slot="card-description"
className={cn(
"text-muted-foreground text-pretty",
size === "lg" ? "text-base" : "text-sm",
className
)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
// In a card a CardLink covers, the action rises above the stretched
// link so its buttons still take their own clicks.
"[[data-slot=card]:has([data-slot=card-link])_&]:relative [[data-slot=card]:has([data-slot=card-link])_&]:z-10",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
// Directly after a BORDERLESS header, close the title-to-content gap to
// 8px so the proximity gradient reads 20 (edge) > 8 (header) > 4
// (title/description) and the title binds to its body. A card title is
// 16px semibold against 14px body: sizes that close together need the
// gap to do the grouping, and at 12px the two read as separate blocks.
// Standalone content keeps py-5.
// That 8px is right for PROSE, and wrong for a FORM. When the content
// holds a field (a label, an input, a select, a switch, a checkbox, a
// radio group), the thing under the description is itself a small
// heading-plus-control group, and at 8px the description sits on the
// first field's label as if it were one more line of it. So the gap opens
// to the `cluster` rung (16px) instead. It is detected with `:has()` so a
// plain CardHeader + CardContent call site is right with no prop to
// remember, and it reads the token through the paren form, which keeps
// it a live var() where a numbered class would be frozen at compile time.
// `:has()` also outranks the plain 8px rule, so the order of the two
// classes does not matter.
// The `:not(.border-b)` scope matters: after the bordered-header recipe
// the rule already separates the regions, so the content region reopens
// at the full 20px rather than hugging the line tighter than the title.
// That holds for a form too, so the bordered case is untouched by both.
// Rows (CardRows) open the gap the same way: a row is its own block,
// and at 8px the first one sat on the description like a line of it.
className={cn(
"px-4 py-5 [[data-slot=card-header]:not(.border-b)+&]:pt-2",
"[[data-slot=card-header]:not(.border-b)+&:has(input,textarea,select,[role=switch],[role=checkbox],[role=radiogroup],[data-slot=label],[data-slot=select-trigger],[data-slot=combobox-trigger],[data-slot=card-rows])]:pt-(--spacing-rhythm-cluster)",
className
)}
{...props}
/>
)
}
/** Body region for table/row-list cards (typically paired with CardTableHeader).
* Its direct children are self-padded rows (own `py` + dividers), so the body
* itself carries only a minimal vertical inset to buffer the first/last row
* from the header and bottom edge - never the default content padding. */
function CardTableBody({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-table-body"
className={cn("px-4 py-1", className)}
{...props}
/>
)
}
/** Groups CardRow children. Card is structure-only, so rows sit flush to the
* bottom edge with no negative-margin hack. */
function CardRows({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-rows"
className={className}
{...props}
/>
)
}
// A clickable row styles the hover itself, since a plain row has none (hover
// implies interactivity). The fill is the neutral tint `subtle` buttons use,
// not `bg-muted`, which would vanish on a card. On a hover-capable pointer the
// rule under the hovered row and the one above it go transparent, so the fill
// is not boxed in by two lines. The sibling rule sits in the media query
// because `hover:` only wraps the row's own variant.
const CARD_ROW_INTERACTIVE =
"w-full cursor-pointer text-start outline-none transition-colors duration-small ease-small hover:border-transparent hover:bg-neutral-500/10 focus-visible:ring-[3px] focus-visible:ring-ring-focus focus-visible:ring-inset [@media(hover:hover)]:[&:has(+[data-interactive]:hover)]:border-transparent"
/** A row in a CardRows list: one line of items by default, a hairline under
* each. Display only unless `render` is given. */
function CardRow({
layout = "row",
inset = "default",
render,
className,
children,
...props
}: React.ComponentProps<"div"> & {
/** `row` (default) lays the children out on one line, vertically centred.
* `block` stacks them in a column that fills the width, for a row of text
* and controls (a title, a summary, a link line). */
layout?: "row" | "stack"
/** `default` pads 16px each side, for a list sitting flush in the card.
* `flush` drops the side padding, for a list inside CardContent, which
* already pads; the first row also loses its top padding and the last its
* bottom, so the list ends on the card's own padding. */
inset?: "default" | "flush"
/** Makes the whole row one link or button: pass the element (`<a href />`,
* `<Link href />`, `<button type="button" />`) and the row's children go
* inside it. Adds a hover fill, a focus ring and a pointer cursor, and the
* dividers around the hovered row disappear. For a row with a chevron, a
* count and one line of description use CardLinkRow instead. */
render?: React.ReactElement<React.HTMLAttributes<HTMLElement>>
}) {
const classes = cn(
"border-b border-border last:border-0",
layout === "stack"
? "flex flex-col items-stretch gap-(--spacing-rhythm-bind)"
: "flex items-center gap-4",
inset === "flush" ? "px-0 py-4 first:pt-0 last:pb-0" : "px-4 py-4",
render && CARD_ROW_INTERACTIVE,
className
)
if (render) {
return React.cloneElement(
render,
{
...props,
"data-slot": "card-row",
"data-interactive": "",
className: cn(classes, render.props.className),
} as React.HTMLAttributes<HTMLElement>,
children
)
}
return (
<div data-slot="card-row" className={classes} {...props}>
{children}
</div>
)
}
/** Compact card header used across dashboard cards: 48px height, title left, optional action right */
function DashboardCardHeader({
title,
nav,
action,
actionInset = "flush",
link,
inset = "default",
className,
...props
}: {
/** A string takes the header's own type treatment. Pass a node when the
* header's identity IS a control (a record picker, a tab set): a node is
* rendered raw, because truncate + font-medium are a label's styling and a
* control brings its own. This slot exists so such a header composes the
* component instead of re-typing its chrome, which is how a fourth card
* header height enters a codebase. */
title: React.ReactNode
/** Line Tabs (or another nav) centred in the band, between the title and
* the action. Centred on the card, not on the gap between the two, so it
* holds its place whatever the title and action measure; the band becomes
* three columns, the outer two equal. */
nav?: React.ReactNode
action?: React.ReactNode
/**
* How the action seats against the right edge.
*
* `flush` (default) puts the action's own box edge on the content inset, so a
* Badge, a count, or a caption aligns with the title opposite it. This is the
* right answer whenever the action's visible edge IS its box edge.
*
* `icon` outdents by 6px, for an action whose box extends past what you see:
* an icon Button or Kebab carries transparent hit-area chrome between the
* glyph and the box edge, and a ghost text button carries side padding. Left
* flush, that chrome pushes the glyph inboard of the inset and the header
* reads lopsided. The outdent seats the GLYPH on the inset instead. It does
* not scale with `inset`: both edges move together, so the correction holds.
*
* The default is `flush` on purpose. A badge or count dropped in unadorned is
* the common case and must look right with no flag; the button case is the
* one that knows it needs chrome compensation, so it is the one that declares
* it.
*/
actionInset?: "icon" | "flush"
/** Standard header link - renders as subtle text button on the right */
link?: { label: string; onClick: () => void }
/**
* Side padding, which must match the BODY's below it.
*
* A card header and the content under it share one left edge, and mixing the
* two tiers is a visible defect rather than a rounding error: the title lands
* 8px inboard of every line beneath it and the card reads as having two left
* edges. So this is a prop, not a `className` override, because the two have
* to be chosen together and a prop is the only version of that choice a
* reader can see at the call site.
*
* `default` (16px) is the row tier: a card of table rows, metrics, list
* items, which is most of them. `loose` (24px) is the prose tier, for a card
* whose body is paragraphs rather than rows; 16px reads thin once a card is
* wide and the lines inside it are long. Nothing else is offered on purpose:
* a third inset is a third left edge to keep in agreement.
*/
inset?: "default" | "loose"
// "title" is omitted as well as "children": a div carries an HTML title
// attribute typed `string`, and intersecting it with this prop is what
// silently pinned the slot to strings.
} & Omit<React.ComponentProps<"div">, "children" | "title">) {
const rightContent = action ? (
// The outdent is opt-in via `actionInset` (see its doc above): only an
// action whose box extends past its glyph wants it, and the default is a
// flush badge/caption/count that must not be pulled off the inset.
// self-stretch: the slot is the band's full height, so an action that
// fills it (line Tabs, whose underline sits on the border) can; anything
// else is still centred by items-center.
<span className={cn("flex items-center self-stretch", actionInset === "icon" && "-me-1.5")}>
{action}
</span>
) : link ? (
<button
onClick={link.onClick}
className="rounded-sm text-xs text-muted-foreground hover:text-foreground transition-colors duration-small ease-small cursor-pointer outline-none focus-visible:ring-[3px] focus-visible:ring-ring-focus pointer-coarse:py-2"
>
{link.label}
</button>
) : null
return (
<div
data-slot="dashboard-card-header"
// h-12: a 32px icon action + 8px breathing each side; 40px left the
// action's hover box 4px off both borders.
className={cn(
"items-center h-12 border-b border-border bg-muted",
inset === "loose" ? "px-6" : "px-4",
nav ? "grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] gap-4" : "flex",
!nav && rightContent && "justify-between",
className
)}
{...props}
>
{typeof title === "string" ? (
<span className="text-sm leading-normal font-medium truncate min-w-0">{title}</span>
) : (
title
)}
{nav ? (
// self-stretch, like the action slot: line Tabs fill the band so
// their underline sits on the border.
<div className="flex self-stretch items-center">{nav}</div>
) : null}
{nav && rightContent ? <div className="flex self-stretch items-center justify-self-end">{rightContent}</div> : rightContent}
</div>
)
}
/** Metric value block for dashboard metric cards: large value, goal line, "to go" line */
function MetricCardValue({
value,
goal,
delta,
unit,
children,
className,
}: {
value: React.ReactNode
/** The line under the value, e.g. "Goal: 262". OPTIONAL: omit it and the line
* is not rendered at all, rather than rendered empty. A metric whose unit
* reads better beside the number belongs in `children`, which is baseline-
* aligned with it. */
goal?: React.ReactNode
delta?: { value: number; label?: string }
unit?: string
/** A short inline annotation beside the value, e.g. a delta Badge. Rendered
* in a zero-height wrapper so it cannot set the row's height and shift the
* line below it, which means it overflows the row rather than growing it:
* keep it small. Anything tall enough to matter (a real control) belongs
* under the value block, not in this slot. */
children?: React.ReactNode
} & Pick<React.ComponentProps<"div">, "className">) {
return (
// Every line here is cap-trimmed, and the gap is therefore the trimmed
// rung. On the plain `pair` rung (4px) with untrimmed boxes this block
// painted 15.4px between the value and the goal and 14.1px between the goal
// and the delta: not only ~3.7x the number it asked for, but UNEVEN, since
// the 20px value sheds more dead space than the 13px lines under it. One
// gap, two different results, which is what read as floaty. Trimmed, both
// paint the rung exactly and match each other.
//
// The rung is `lines`, not `trim-pair`. Both are the trimmed rendering
// of a tight binding and both now sit at 12px, the way `bind`, `label` and
// `help` share 8px: same number, different question, and they are free to
// move apart again. `trim-pair` is the TWO-line case, a title and the
// one description under it; `lines` is three or more short lines reading as
// one unit, and it fills a real hole in the ladder, which jumped 8 to 16.
// Name the one you mean, because whichever gets re-tuned next, only the
// call sites asking that question should follow it.
//
// The trim goes on the value SPAN, not the row around it: a flex container
// establishes no inline formatting context, so it has no line boxes and
// `text-box-trim` on it would be silently inert. The span is a flex item,
// so it is blockified and does have them. `items-baseline` is unaffected,
// since trimming moves the box, never the baseline.
<div
data-slot="metric-card-value"
className={cn("flex flex-col", className)}
style={{ gap: "var(--spacing-rhythm-lines)" }}
>
{/* THE BADGE MUST NOT SET THIS ROW'S HEIGHT, or the line under it moves.
A baseline-aligned row is as tall as `max(above-baseline) +
max(below-baseline)`. Cap-trimming the value took its below-baseline
extent to ZERO, which is the point, but it also handed that edge to
whatever else is in the row: a `sm` Badge hangs about 5.7px under the
baseline, so a card WITH a badge grew 5.7px taller than one without
and its goal line sat lower. Three cards in a row, two with badges,
three different second-line positions.
The zero-height wrapper is what fixes it. The badge contributes
nothing to the row's cross size and overflows it instead, centred on
the number's cap box, which is where a pill beside a number wants to
sit anyway. The overflow is ~3px each way, well inside CardContent's
20px padding, so nothing clips.
This is why the slot is for a SHORT INLINE ANNOTATION and not a
control: something 32px tall would overflow 16px each way and reach
the goal line 12px below. */}
<div className="flex items-baseline gap-2">
<span className="cap-trim text-xl font-semibold tabular-nums">{value}</span>
{children && (
<span className="flex h-0 shrink-0 items-center self-center">{children}</span>
)}
</div>
{/* CONDITIONAL, because an empty one is not free. This span is a flex item
in a `gap: lines` column, and gap applies BETWEEN items whatever their
size, so a card passing no `goal` paid a full 12px of dead space under
its value for a line with nothing in it. Rendering no element is the
only way to render no gap.
`!= null` on purpose, so it catches undefined and null and nothing
else: a caller passing `0` or `""` asked for that line and gets it. */}
{/* ONE LINE, ending in an ellipsis. A wrapped goal line made one card in
a row a line taller, which pushed its content down against its
neighbours. The sideways cut is `overflow-x-clip`, never `truncate`:
truncate's overflow-hidden clips BOTH axes, and this line is
cap-trimmed, so its box ends at the baseline and every descender
(the p in a URL, a comma) paints below it and was cut off. `clip` on
one axis leaves the other visible, which `hidden` cannot, and
`text-overflow` still applies to it. */}
{goal != null && (
<span className="cap-trim min-w-0 overflow-x-clip text-ellipsis whitespace-nowrap text-xs text-muted-foreground">
{goal}{unit && ` ${unit}`}
</span>
)}
{delta !== undefined && delta.value > 0 && (
<span className="cap-trim text-xs text-subtle-foreground">{delta.label ?? `${delta.value.toLocaleString("en-US")} to go`}</span>
)}
{delta !== undefined && delta.value <= 0 && (
<span className="cap-trim text-xs text-subtle-foreground">Goal reached!</span>
)}
</div>
)
}
/** Table-style column header row for data cards. Pass the same grid classes as the body rows. */
function CardTableHeader({
columns,
gridClassName,
className,
}: {
columns: string[]
/** Grid classes matching the body rows, e.g. "grid-cols-[10rem_1fr_5rem]" */
gridClassName: string
className?: string
}) {
return (
// The wrapper is the size container, so the header answers to the card's
// width and not the viewport's: a narrow card on a wide screen hides it too.
<div className="@container">
<div
data-slot="card-table-header"
className={cn(
"hidden @md:grid items-center gap-8 px-4 py-3 border-b border-border bg-muted text-2xs font-semibold uppercase tracking-wide text-muted-foreground",
gridClassName,
className
)}
>
{columns.map((col, i) => (
<span key={`${col}-${i}`}>{col}</span>
))}
</div>
</div>
)
}
function CardFooter({
size = "default",
tone = "default",
className,
...props
}: React.ComponentProps<"div"> & {
/**
* `default` gives the bordered band 20px above and below its actions, which
* suits a card read on its own. `compact` gives 12px, for a dense grid of
* cards (a dashboard) where a 68px band under every card eats the rows the
* cards exist to show: with a `sm` button it lands at 52px, close to the
* header above it. Both keep the band symmetric, for the reason below.
*/
size?: "default" | "compact"
/** `muted` paints the footer as a band: a rule above and the muted fill,
* the same band `TableFooter` ships, so a card's buy row or totals row
* reads as a pair with a table's. `bg-muted` is one step off the card in
* both modes (neutral-100 on 50 in light, 800 on 900 in dark). The card
* clips the band to its corners. */
tone?: "default" | "muted"
}) {
return (
<div
data-slot="card-footer"
data-size={size}
data-tone={tone}
// No top padding by default: the content above already ends on its own
// pb-5, so the footer borrows that 20px. A `border-t` cuts the borrowed
// space off at the line, which leaves the actions in a closed band with
// a rule above and the card edge below. Both are lines of the same
// weight, so the eye centers the buttons between them and any asymmetry
// reads as a mistake: the bordered footer therefore restores its own
// 20px on its side of the rule. This used to be a caller-supplied
// `pt-4`, which shipped a band that was 16 above and 20 below.
className={cn(
"flex items-center px-4",
size === "compact" ? "pb-3 [&.border-t]:pt-3" : "pb-5 [&.border-t]:pt-5",
tone === "muted" && "border-t border-border bg-muted",
className
)}
{...props}
/>
)
}
// The card's title as a link that covers the whole card, so the card is one
// target with no anchor wrapped around block content. Put it inside CardTitle.
// No hover fill: a card is a surface, not a row, and filling a whole card on
// hover reads as a selection. The focus ring is drawn on the stretched layer,
// inside the card's corners. Pass `render={<Link href="..." />}` to use a
// router link; plain `href` renders an `<a>`.
// A CardAction in the same card rises above the stretched link on its own, and
// CardMedia lets clicks through to it, so neither needs a class at the call
// site. Any other control inside the card still needs `relative z-10`.
function CardLink({
render,
className,
children,
...props
}: React.ComponentProps<"a"> & {
render?: React.ReactElement<React.HTMLAttributes<HTMLElement>>
}) {
const classes = cn(
"outline-none after:absolute after:inset-0 after:rounded-lg focus-visible:after:ring-[3px] focus-visible:after:ring-inset focus-visible:after:ring-ring-focus",
className
)
if (render) {
return React.cloneElement(
render,
{ ...props, "data-slot": "card-link", className: cn(classes, render.props.className) } as React.HTMLAttributes<HTMLElement>,
children
)
}
return (
<a data-slot="card-link" className={classes} {...props}>
{children}
</a>
)
}
export {
Card,
CardLink,
CardMedia,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
CardTableBody,
CardRows,
CardRow,
CardTableHeader,
DashboardCardHeader,
MetricCardValue,
}"use client"
import * as React from "react"
import { cn } from "@/registry/lib/utils"
// @use-when a card whose content changes size and should grow or shrink
// smoothly instead of jumping.
/** True when a descendant is currently animating its OWN height (e.g. an inner
* Collapsible's disclosure height transition). We scope the query to `inner` so the
* card's own height transition - which lives on the OUTER element, outside
* `inner`'s subtree - never counts as a child animation (that would make the
* card yield to itself and kill the snap animation). We match on the animated
* property, so unrelated motion (a spinner, the trigger's chevron rotate)
* doesn't suppress height animation. */
function isChildAnimatingHeight(inner: HTMLElement) {
if (typeof inner.getAnimations !== "function") return false
return inner.getAnimations({ subtree: true }).some((a) => {
// "pending" is a real play state browsers report but the DOM lib type omits.
const state = a.playState as string
if (state !== "running" && state !== "pending") return false
const transitionProperty = (a as CSSTransition).transitionProperty
if (transitionProperty) {
return transitionProperty === "height" || transitionProperty === "all"
}
try {
const effect = a.effect as KeyframeEffect | null
return effect?.getKeyframes().some((k) => "height" in k) ?? false
} catch {
return false
}
})
}
/**
* Card shell that smoothly animates its OWN height when content size changes.
* Opt-in via `<Card animateHeight>`.
*
* Structure: the height-controlled box is the OUTER element; the children live
* in an INNER wrapper whose height is never touched, so its measured height is
* always the true content height (reading `scrollHeight`/`clientHeight` on the
* box we resize would feed our own value back in - `scrollHeight >= clientHeight`).
*
* Behaviour, per content change:
* - If a descendant is animating its own height (an inner Collapsible), we
* YIELD - clear our height so the card follows that animation 1:1 for free.
* Imposing our own transition here is the "two animations racing" bug.
* - Otherwise the change is a snap (conditional render, swapped content): pin
* the old height, force a reflow, transition to the new height, release back
* to `auto` on transitionend.
*
* Honors prefers-reduced-motion (no observer → native snap). `height` is the
* sanctioned motion exception; 200ms ease-out matches the Collapsible reveal.
* Overflow is clipped inline only while a height animation runs and cleared in
* `release`, so a non-card host (a dialog body) clips mid-animation but returns
* to visible at rest; a Card keeps clipping either way via its base class.
*/
function AnimatedCardShell({ className, children, ...props }: React.ComponentProps<"div">) {
const outerRef = React.useRef<HTMLDivElement>(null)
const innerRef = React.useRef<HTMLDivElement>(null)
const prev = React.useRef<number | null>(null)
React.useEffect(() => {
const outer = outerRef.current
const inner = innerRef.current
if (!outer || !inner) return
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
const release = (e: TransitionEvent) => {
if (e.target !== outer || e.propertyName !== "height") return
outer.style.height = ""
outer.style.transition = ""
// Cleared back to the stylesheet, not forced visible: a Card's base class
// still clips its corners (overflow-clip), so cards keep clipping. A non-card host
// (a dialog body) returns to visible, so focus rings are not clipped at
// rest - only while a height animation is actually running.
outer.style.overflow = ""
}
const follow = () => {
outer.style.height = ""
outer.style.transition = ""
outer.style.overflow = ""
}
const observer = new ResizeObserver(() => {
const next = inner.offsetHeight
// Mid-flight (inline height still set): retarget from the LIVE rendered height,
// not the cached previous target - rapid successive changes must reverse smoothly.
// Settled (auto height): outer has already snapped to the new content height by
// observer time, so the cached previous measurement is the only true from value.
const inFlight = outer.style.height !== ""
const from = inFlight ? outer.offsetHeight : prev.current
prev.current = next
// First measure records the baseline - no animation on mount.
if (from === null || from === next) return
// A child is driving its own height - ride along instead of fighting it.
if (isChildAnimatingHeight(inner)) return follow()
// Snap: animate the card's height across the discrete jump. Clip while
// the box is shorter than its content, or a grow reveals the new content
// spilling below the animating edge. Released in `release` on transitionend.
outer.style.overflow = "hidden"
outer.style.height = `${from}px`
outer.getBoundingClientRect() // force reflow so the next assignment animates
outer.style.transition = "height var(--transition-duration-large) var(--ease-large)"
outer.style.height = `${next}px`
})
// Observe the untouched inner wrapper, never the box we resize.
observer.observe(inner)
outer.addEventListener("transitionend", release)
return () => {
observer.disconnect()
outer.removeEventListener("transitionend", release)
}
}, [])
return (
<div ref={outerRef} data-slot="card" className={cn(className)} {...props}>
<div ref={innerRef} className="flex flex-col">
{children}
</div>
</div>
)
}
export { AnimatedCardShell }export const cardDotgridClass =
"bg-[radial-gradient(color-mix(in_oklab,var(--color-neutral-500)_15%,transparent)_1px,transparent_1px)] [background-size:12px_12px]"
// Directive-free, so a Server Component (the docs preview frame) can read the
// string as well as Card. The dots are the root's background-image, so they sit
// behind the card's content. The card's own `bg-card` supplies the fill.