Aspect Ratio

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

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

Architecture

  • Root: The root component which contains the aspect ratio logic

Structure

Here's an overview of how the Aspect Ratio component is structured in code:

	<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";
 
  let {
    src,
    alt,
    ref = $bindable(null),
    imageRef = $bindable(null),
    ...restProps
  }: WithoutChildrenOrChild<AspectRatio.RootProps> & {
    src: string;
    alt: string;
    imageRef?: HTMLImageElement | null;
  } = $props();
</script>
 
<AspectRatio.Root {...restProps} bind:ref>
  <img {src} {alt} bind:this={imageRef} />
</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"
  alt="an abstract painting"
  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 Details
ratio
ref
children
child
Data Attribute Details
data-aspect-ratio-root