Installation
Install the dependencies
pnpm add cn class-variance-authorityCopy the component
Copy the following files into src/lib/components/ui/aspect-ratio.
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements';
import { cn } from 'cn';
let { ratio, children, class: classProp, ...props }: HTMLAttributes<HTMLDivElement> & { ratio: number } = $props();
</script>
<div data-slot="aspect-ratio" {...props} style:--ratio={ratio} class={cn('relative aspect-(--ratio)', classProp)}>
{@render children?.()}
</div>import type { ComponentProps } from 'svelte';
import AspectRatio from './AspectRatio.svelte';
export { AspectRatio };
export type AspectRatioProps = ComponentProps<typeof AspectRatio>;Update the import paths
Change the imports to match your project setup.
Usage
<script lang="ts">
import { AspectRatio } from '$lib/components/ui/aspect-ratio';
</script><AspectRatio ratio={16 / 9}>
<img src="..." alt="A mountain lake" class="rounded-md object-cover" />
</AspectRatio>