Media & presentationExplore · Adapt · Compose

Aspect Ratio

Keeps embedded media in a fixed width-to-height ratio using CSS aspect-ratio (shadcn-style API; no Radix dependency). Give media a predictable place in the layout while keeping the surrounding content readable during loading, playback or failure. Explore the live examples, inspect their source and choose the composition that fits your interface before connecting it to your application's data.

The examples use @/components/kamod-ui/aspect-ratio in a Preact project. Follow the live result and its source together: compare supported options in the API reference, refine presentation with the component styles guide, and use shared theme tokens for consistent colors and surfaces. Preserve keyboard behavior and meaningful labels as you replace the sample content.

In this guide 7 sections
Interactive previewTry it before you copy it
Live Preact example Local preview theme · Responsive styles follow the preview width

Installation

Import AspectRatio from @/components/kamod-ui/aspect-ratio.

pnpm add @kamod-ch/ui

The @/components/kamod-ui/… imports in these examples refer to local source files. Configure that alias when copying source, or use the corresponding exports from @kamod-ch/ui when installing the package. Connect the global theme CSS and Tailwind source detection before your first render.

import { AspectRatio } from "@/components/kamod-ui/aspect-ratio"
import { Image } from "@/components/kamod-ui/image";

Usage

Pass ratio as a number (e.g. 16/9). Put the image (or video) inside and size it with h-full w-full object-cover so it fills the box.

import { AspectRatio } from "@/components/kamod-ui/aspect-ratio";

Choose a complete composition from the examples below; required child components and props vary by pattern.

Interactive previewTry it before you copy it
Live Preact example Local preview theme · Responsive styles follow the preview width

Component examples & variants

Explore Aspect Ratio in different contexts, from the starting pattern to the compositions below. Begin with Demo, then compare the examples that match your content, state and layout. These are working patterns to adapt, not a list of interchangeable variant values: check the API reference before using a prop or combining behaviors. Look at the surrounding labels, supporting text and spacing as well as the component itself.

Read the result and its implementation together. Use each showcase’s Code view to inspect imports and composition, or its Prompt view to prepare a setup or adaptation brief. Try the narrow preview and local theme controls before connecting real data, and use Reset to return an example to its initial state. Keep layout changes in class utilities where appropriate; follow the component styles guide for hierarchy and the theming guide for shared surfaces and colors. The accessibility notes explain what to preserve when making those changes.

Demo

Default widescreen frame with muted background and rounded corners.

Interactive previewTry it before you copy it
Live Preact example Local preview theme · Responsive styles follow the preview width

Square

Use ratio={1 / 1} for square thumbnails or avatars.

Interactive previewTry it before you copy it
Live Preact example Local preview theme · Responsive styles follow the preview width

Portrait

Use ratio={9 / 16} for vertical media.

Interactive previewTry it before you copy it
Live Preact example Local preview theme · Responsive styles follow the preview width
API reference

Props and data

Configure Aspect Ratio using the contracts below. Read the documented options alongside the source definitions to understand which values your application supplies and which details the component owns. Start with a prop or helper, then follow its type link to inspect the declaration without leaving the page.

Component overview.

Type cards are extracted from this checkout’s TypeScript source at build time. Props inherited through HTMLAttributes, Omit or variant helpers remain references in those declarations; their fields are not flattened here. Match the reference to your installed version, and check a package’s exports before writing an import type. A type exported by a source file is not necessarily re-exported by @kamod-ch/ui.TypeScript

Component props

Read each option with its owning component. The
marker identifies required fields verified in that declaration. A ? means a field can be omitted; it does not promise a fallback value. Existing documented defaults remain alongside the descriptions. For callbacks, check the argument and return types before connecting your own state or services.

AspectRatio

Wrapper with CSS aspect-ratio; clip overflow. Child media should fill with h-full w-full object-cover.

AspectRatio documented props
Prop / typeDescription
ratio
numberAspectRatioProps

Width ÷ height (e.g. `16 / 9`, `1`, `9 / 16`). Applied as CSS `aspect-ratio`.

Documented default(required)

class
stringAspectRatioProps

Documented class option for AspectRatio. Check its type alongside the usage examples before supplying a value.

Documented default-

children
ComponentChildrenAspectRatioProps

Documented children option for AspectRatio. Check its type alongside the usage examples before supplying a value.

Documented default-

Data type reference

Expand a card to inspect and copy the exact declaration. The code header identifies its repository file; follow imported or inherited types in the implementation source when you need the complete dependency chain. Required-field summaries cover fields declared directly in that type. Source-only helpers and inferred schema outputs describe the local implementation, not additional props you can pass to every component.

AspectRatioProps
Exported source declaration from AspectRatio.tsx. Referenced types retain their original names; inspect that file for imports and supporting definitions.
Required fields
ratio

Accessibility

Build the complete interaction, including the parts outside Aspect Ratio. The notes below distinguish the current implementation from the labels, content and behavior your application supplies. Start with the live preview, check the props and data reference, and test the finished composition with real content rather than assuming that an unchanged visual example covers every use case.

Built-in behavior and defaults

AspectRatio reserves a proportional layout box. It does not add an accessible name, image alternative, media controls or a semantic figure. Those responsibilities remain with the content placed inside it.

Labels and relationships

Name informative images, videos or embedded content through their own APIs. When media needs a caption, compose a figure and figcaption or other appropriate structure around the visual box. Do not announce the numerical aspect ratio unless it matters to the task.

Keyboard and focus

Static media wrappers should not enter the tab order. Any embedded player or interactive content must remain keyboard reachable at the constrained size, with controls and focus indicators visible rather than cropped.

States and integration details

A predictable ratio can still hide important content if object-cover crops labels or diagrams. Provide a readable alternative for information that no longer fits and avoid fixed-height assumptions around captions or enlarged text.

Verify the complete interaction

Check behavior as well as markup. Work through these scenarios in the application where the component will be used. Automated checks can help find structural problems; also review the reading experience with a screen reader, keyboard focus and the actual feedback from your application.

  1. Inspect the inner media's name and alternative description rather than only the wrapper.
  2. Resize the container and confirm captions, controls and focus indicators remain available.
  3. Try missing media and text enlargement without collapsing the surrounding reading order.

Recheck the result after changing theme tokens, translations or class overrides. Include text enlargement, narrow layouts and reduced-motion settings where animation is present. Inspect the component source when a behavior differs from your expectation; a role or state attribute does not implement keyboard interaction by itself.

For background, read the WAI-ARIA authoring guidance and keyboard interface guidance. These explain the patterns; verify browser and assistive-technology behavior for the implementation and audience you actually support.

Build it into your interface

Use the Aspect Ratio examples as a starting point, then review the behavior in the context of your own screen. Layout, state and content should work together.

Connect the behavior

Choose a meaningful alternative description when media conveys information; decorative media should not repeat surrounding labels. Reserve space before assets load, supply a useful fallback, and keep playback or carousel movement under the user's control.

Copy the composition, then connect its intent. Replace sample records and callbacks with your own data flow. For options such as value, defaultValue, open or onChange, use only those documented in this component's API; different components expose different contracts.

Give each piece of state one owner. Keep a temporary selection inside the interface when nothing else needs it; lift shared values into a parent when other controls depend on them. Read the prop reference before combining controlled values with defaults. A default normally initializes a control; it is not a substitute for updating its current value.

Connect requests in an event handler or your application’s data layer, never as a side effect of rendering. Keep pending, completed and failed outcomes distinct, preserve useful input after an error, and offer a clear recovery action. If the integration subscribes to an external source, remove that subscription when its owner unmounts; cancel or ignore obsolete requests so an earlier response cannot replace newer results.

Start with the live preview, then exercise the same interaction with your actual data. The type definitions describe accepted values; they do not implement persistence, navigation or server-side validation for you. Keep those responsibilities in the application that composes the UI.

Refine the presentation

Let a parent own the surrounding spacing. Keep related elements together with gap and use semantic surface/foreground pairs so the composition follows the active theme. The wrapper below changes the surrounding layout without assuming extra props on Aspect Ratio.

src/components/ExampleSurface.tsx
import type { ComponentChildren } from "preact";

export function ExampleSurface({ children }: { children: ComponentChildren }) {
  return (
    <div class="grid min-w-0 gap-4 rounded-lg border border-border bg-card p-4 text-card-foreground sm:p-6">
      {children}
    </div>
  );
}

Put the chosen example inside ExampleSurface, then refine supported variants and sizes using the API above. For application-wide changes, adjust theme tokens instead of repeating fixed colors. See Component styles for hierarchy, density and focus treatments.

Review the complete interaction

  • Try missing and slow assets, different aspect ratios and long alternative text.
  • Check controls with the keyboard and keep automatic movement compatible with reduced motion.
  • Review cropping at narrow widths so the subject and any important text remain visible.

The preview's narrow control changes its container width. Also resize the browser when checking viewport-based Tailwind utilities such as sm: and md:, and test overlays in the full page where their portals render.

Compose a complete interface

Aspect Ratio is one part of the interaction. Choose companion components for the information or actions that still need a place on the screen. The references below are suggestions to compose deliberately, not extra dependencies you must add to every example.

Keep one source of truth for the operation and let each component communicate a different part of it. For example, waiting, no results and failure need different explanations. Avoid showing contradictory states together, and keep recovery actions close to the message that explains them.

Start with the smallest composition that explains the task. Browse the component library for individual controls or the block collections for complete layouts. Reuse shared theme tokens so these pieces feel consistent in light and dark mode.

Sources & design references

Follow Aspect Ratio from its implementation to the ideas behind your own composition. Start with the local API, explore a visual direction, then bring the result back to your app’s shared styles.

Implementation · Preact

Kamod UI implementation

Start with the code that powers this page. The Aspect Ratio source in Kamod UI is the implementation reference. Use the installation guide for setup and the API reference for supported props, composition and events before adapting an example.

Source locationpackages/core/src/components/aspect-ratio

Compare imports, default values and state handling with the example you chose. The repository’s main branch can be ahead of your installed version; check your package.json and lockfile when an API differs. Retain applicable license notices when reusing source.

Visual reference · Independently maintained

Explore the visual possibilities

Browse the Aspect Ratio collection on Shadcnblocks to compare hierarchy, density and composition. Look at how labels, supporting text and surrounding space work together, then choose the details that help your own content read clearly.

Reference credit: Shadcnblocks. These independently maintained React examples are visual references; this link does not claim they authored Kamod’s Preact implementation. Check the original example’s license before reusing its code or assets, and use this page’s API when building the Kamod version.

Bring it back to your app

A reference becomes useful when it fits your real content. Work through these decisions in order:

  1. Keep the behavior grounded. Start with the interactive examples, then connect your data and callbacks using the integration guidance. Preserve labels, keyboard access and disabled states as you change the presentation.
  2. Make the styling repeatable. Use the styles guide for local class adjustments and theming documentation for shared color decisions. Keep semantic surface and foreground pairs together in both light and dark mode.
  3. Check the complete screen. See how components combine in the block collections, then try long labels, loading states and narrow layouts in your own composition. The Theme Toggle guide helps you expose a scheme switch in the finished interface.