Skip to content
2k
On This Page

Aspect Ratio

Displays content within a desired ratio.

Solid logo artwork
import { AspectRatio } from "~/components/ui/aspect-ratio"

export default function AspectRatioDemo() {
  return (
    <div class="w-full max-w-sm">
      <AspectRatio ratio={16 / 9} class="rounded-lg bg-muted">
        <img
          src="/solid-brand/launch-light.svg"
          alt="Solid logo artwork"
          class="size-full rounded-lg object-cover"
        />
      </AspectRatio>
    </div>
  )
}

Installation

pnpm dlx solidui-cli@latest add aspect-ratio

Copy and paste the following code into your project.

components/ui/aspect-ratio.tsx
import { type ComponentProps } from "@solidjs/web"
import { omit } from "solid-js"

import { cn } from "~/lib/utils"

type AspectRatioProps = ComponentProps<"div"> & {
  ratio: number
  class?: string | undefined
}

const AspectRatio = (props: AspectRatioProps) => {
  const others = omit(props, "class", "ratio")
  return (
    <div
      data-slot="aspect-ratio"
      style={{
        "--ratio": props.ratio
      }}
      class={cn("relative aspect-(--ratio) overflow-hidden", props.class)}
      {...others}
    />
  )
}

export { AspectRatio }

Update the import paths to match your project setup.

Usage

import { AspectRatio } from "~/components/ui/aspect-ratio"
<AspectRatio ratio={16 / 9}>
  <img
    src="/photo.jpg"
    alt="Mountain landscape"
    class="size-full object-cover"
  />
</AspectRatio>

Square

A square aspect ratio component using the ratio={1 / 1} prop. This is useful for displaying images in a square format.

Solid logo artwork
import { AspectRatio } from "~/components/ui/aspect-ratio"

export default function AspectRatioSquare() {
  return (
    <div class="w-full max-w-[12rem]">
      <AspectRatio ratio={1 / 1} class="rounded-lg bg-muted">
        <img
          src="/solid-brand/launch-light.svg"
          alt="Solid logo artwork"
          class="size-full rounded-lg object-cover"
        />
      </AspectRatio>
    </div>
  )
}

Portrait

A portrait aspect ratio component using the ratio={9 / 16} prop. This is useful for displaying images in a portrait format.

Solid logo artwork
import { AspectRatio } from "~/components/ui/aspect-ratio"

export default function AspectRatioPortrait() {
  return (
    <div class="w-full max-w-[10rem]">
      <AspectRatio ratio={9 / 16} class="rounded-lg bg-muted">
        <img
          src="/solid-brand/launch-light.svg"
          alt="Solid logo artwork"
          class="size-full rounded-lg object-cover"
        />
      </AspectRatio>
    </div>
  )
}

API Reference

AspectRatio

The AspectRatio component displays content within a desired ratio.

PropType
rationumber
classstring