Aspect Ratio

Displays content while maintaining a specified aspect ratio, ensuring consistent visual proportions.

an abstract painting
	<script lang="ts">
  import { AspectRatio } from "bits-ui";
</script>
 
<AspectRatio.Root ratio={14 / 9} class="scale-80 rounded-[15px] bg-transparent">
  <img
    src="/abstract.png"
    alt="an abstract painting"
    class="h-full w-full rounded-[15px] object-cover"
  />
</AspectRatio.Root>

Structure

	<script lang="ts">
	import { AspectRatio } from "bits-ui";
</script>
 
<AspectRatio.Root />

Reusable Component

If you plan on using a lot of AspectRatio components throughout your application, you can create a reusable component that combines the AspectRatio.Root and whatever other elements you'd like to render within it. In the following example, we're creating a reusable MyAspectRatio component that takes in a src prop and renders an img element with the src prop.

MyAspectRatio.svelte
	<script lang="ts">
	import { AspectRatio, type WithoutChildrenOrChild } from "bits-ui";
	import Image from "phosphor-svelte/lib/Image";
 
	let {
		src,
		...restProps
	}: WithoutChildrenOrChild<AspectRatio.RootProps> & {
		src: string;
	} = $props();
</script>
 
<AspectRatio.Root {...restProps}>
	<Image {src} alt="an abstract painting" />
</AspectRatio.Root>

You can then use the MyAspectRatio component in your application like so:

+page.svelte
	<script lang="ts">
	import MyAspectRatio from "$lib/components/MyAspectRatio.svelte";
</script>
 
<MyAspectRatio src="https://example.com/image.jpg" ratio={4 / 3} />

Custom Ratio

Use the ratio prop to set a custom aspect ratio for the image.

	<AspectRatio.Root ratio={16 / 9}>
	<!-- ... -->
</AspectRatio.Root>

API Reference

AspectRatio.Root

The aspect ratio component.

Property Type Description
ratio
number

The desired aspect ratio.

Default: 1
ref bindable prop
HTMLDivElement

The underlying DOM element being rendered. You can bind to this to get a reference to the element.

Default: undefined
children
Snippet

The children content to render.

Default: undefined
child
Snippet

Use render delegation to render your own element. See delegation docs for more information.

Default: undefined
Data Attribute Value Description
data-aspect-ratio-root
''

Present on the root element.