AspectRatio 宽高比

把内容固定在给定的宽高比内。

ATRI

ATRI

封面按 3:4 裁切,不同尺寸的原图都能对齐。

import { AspectRatio, Card, Image, Stack, Text } from '@hina-ui/react'

export default function Demo() {
  return (
    <Card className="w-full max-w-xs" padded={false}>
      <AspectRatio ratio={3 / 4} className="overflow-hidden rounded-t-lg">
        <Image src="/sample.webp" alt="ATRI" className="size-full" />
      </AspectRatio>
      <Stack gap="xs" className="p-4">
        <Text className="font-medium">ATRI</Text>
        <Text tone="muted" size="sm">
          封面按 3:4 裁切,不同尺寸的原图都能对齐。
        </Text>
      </Stack>
    </Card>
  )
}
tsx

用法

import { AspectRatio } from '@hina-ui/react'
ts

ratio 是宽除以高,默认为 16 / 9。容器的高度由宽度和这个比值算出,因此不同尺寸的图片放入后外框一致。

夏日午后的坡道
import { AspectRatio, Image } from '@hina-ui/react'

export default function Demo() {
  return (
    <AspectRatio className="bg-inset w-full max-w-md overflow-hidden rounded-md">
      <Image src="/sample.webp" alt="夏日午后的坡道" className="size-full" />
    </AspectRatio>
  )
}
tsx

示例

常见比例

写成除法表达式比写小数更好认,例如 ratio={3 / 4}。

1 / 1

夏日午后的坡道

4 / 3

夏日午后的坡道

16 / 9

夏日午后的坡道

3 / 4

夏日午后的坡道
import { AspectRatio, Image, Inline, Stack, Text } from '@hina-ui/react'

const ratios = [
  { label: '1 / 1', value: 1 },
  { label: '4 / 3', value: 4 / 3 },
  { label: '16 / 9', value: 16 / 9 },
  { label: '3 / 4', value: 3 / 4 },
]

export default function Demo() {
  return (
    <Inline align="start" className="gap-4">
      {ratios.map(ratio => (
        <Stack key={ratio.label} gap="xs" className="w-32">
          <Text tone="muted" size="sm">
            {ratio.label}
          </Text>
          <AspectRatio ratio={ratio.value} className="bg-inset overflow-hidden rounded-md">
            <Image src="/sample.webp" alt="夏日午后的坡道" className="size-full" />
          </AspectRatio>
        </Stack>
      ))}
    </Inline>
  )
}
tsx

嵌入内容

内部的元素占满整个框。图片和视频已经预设为 object-fit: cover,会填满框并裁去多余部分;iframe 等元素自身占满即可。

此处可放置 iframe 或 video,它会占满整个框

import { AspectRatio, Center, Text } from '@hina-ui/react'

export default function Demo() {
  return (
    <AspectRatio className="bg-inset w-full max-w-md overflow-hidden rounded-md">
      <Center className="size-full">
        <Text tone="muted" size="sm">
          此处可放置 iframe 或 video,它会占满整个框
        </Text>
      </Center>
    </AspectRatio>
  )
}
tsx

API

属性
类型
默认值
说明
ratio
number
16 / 9
宽高比,宽除以高
className
string
—
追加至外层容器的类名
属性
说明
children
框内内容