Aspect Ratio

Layout

Container that maintains a fixed aspect ratio.

Preview

16:9

Usage

example.jsx
import { AspectRatio } from "@/components/ui/aspect-ratio";

export default function Example() {
  return <AspectRatio />;
}

Source Code

Copy this file into components/ui/aspect-ratio.jsx in your project.

aspect-ratio.jsx
import { forwardRef } from "react";
import { cn } from "@/lib/utils";

const AspectRatio = forwardRef(({ className, ratio = 16 / 9, children, ...props }, ref) => (
  <div ref={ref} className={cn("relative w-full", className)} style={{ paddingBottom: `${(1 / ratio) * 100}%` }} {...props}>
    <div className="absolute inset-0">{children}</div>
  </div>
));
AspectRatio.displayName = "AspectRatio";

export { AspectRatio };

Quick Install

Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.

npm install clsx tailwind-merge