AspectRatio 宽高比

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

ATRI

ATRI

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

<script setup lang="ts">
  import { AspectRatio, Card, Image, Stack, Text } from '@hina-ui/vue'
</script>

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

用法

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

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

夏日午后的坡道
<script setup lang="ts">
  import { AspectRatio, Image } from '@hina-ui/vue'
</script>

<template>
  <AspectRatio class="bg-inset w-full max-w-md overflow-hidden rounded-md">
    <Image src="/sample.webp" alt="夏日午后的坡道" class="size-full" />
  </AspectRatio>
</template>
vue

示例

常见比例

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

1 / 1

夏日午后的坡道

4 / 3

夏日午后的坡道

16 / 9

夏日午后的坡道

3 / 4

夏日午后的坡道
<script setup lang="ts">
  import { AspectRatio, Image, Inline, Stack, Text } from '@hina-ui/vue'

  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 },
  ]
</script>

<template>
  <Inline align="start" class="gap-4">
    <Stack v-for="ratio in ratios" :key="ratio.label" gap="xs" class="w-32">
      <Text tone="muted" size="sm">{{ ratio.label }}</Text>
      <AspectRatio :ratio="ratio.value" class="bg-inset overflow-hidden rounded-md">
        <Image src="/sample.webp" alt="夏日午后的坡道" class="size-full" />
      </AspectRatio>
    </Stack>
  </Inline>
</template>
vue

嵌入内容

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

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

<script setup lang="ts">
  import { AspectRatio, Center, Text } from '@hina-ui/vue'
</script>

<template>
  <AspectRatio class="bg-inset w-full max-w-md overflow-hidden rounded-md">
    <Center class="size-full">
      <Text tone="muted" size="sm">此处可放置 iframe 或 video,它会占满整个框</Text>
    </Center>
  </AspectRatio>
</template>
vue

API

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