Aspect Ratio

Displays content in a desired ratio.

Usage

AspectRatioExample.tsx
  1. 1
  2. 2
  3. 3
<AspectRatio ratio={16 / 9}>
<img src="https://images.unsplash.com/photo-1558728112-33eea323814f" alt="Sunrise over the sea, by Sarah Lee on Unsplash" className="h-full w-full rounded-xl object-cover" />
</AspectRatio>

Here's the <AspectRatio /> component in action.

Sunrise over the sea, by Sarah Lee on Unsplash

Features

  • Accepts any custom ratio.

Parts and their API

AspectRatio

Displays content within a desired ratio.

Props

PropTypeDefaultDescription
rationumber1The ratio to display the content within.

Source

aspect-ratio.tsx
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
import { type HTMLAttributes, type PropsWithChildren, forwardRef } from 'react'
import { cn } from '#app/utils/tailwind-merge.ts'
type AspectRatioProps = PropsWithChildren<HTMLAttributes<HTMLDivElement>> & {
ratio?: number
}
/**
* AspectRatio component.
*
* @component
* @example
* ```jsx
* <AspectRatio ratio={16 / 9}>
* <img src={blueSkies} alt="By Sarah Lee on Unsplash" className="h-full w-full rounded-xl object-cover" />
* </AspectRatio>
* ```
*
* @param {number} [ratio=1] - The aspect ratio.
* @param {string} [className] - Additional CSS class names.
* @param {React.HTMLAttributes<HTMLDivElement>} [props] - Additional HTML attributes.
* @returns {JSX.Element} The AspectRatio component.
*/
const AspectRatio = forwardRef<HTMLDivElement, AspectRatioProps>(({ ratio = 1 / 1, className, ...props }, forwardedRef) => {
return (
<div className="relative w-full" style={{ paddingBottom: `${100 / ratio}%` }}>
<div ref={forwardedRef} className={cn(`absolute top-0 right-0 bottom-0 left-0`, className)} {...props} />
</div>
)
})
AspectRatio.displayName = 'AspectRatio'
export { AspectRatio }