본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

화면 비율(Aspect Ratio)

원문 보기 위키 갱신

이미지나 영상 같은 콘텐츠를 항상 일정한 가로세로 비율 안에 담아주고 싶을 때가 있죠. Aspect Ratio 컴포넌트는 지정한 비율을 유지하면서 내부 콘텐츠를 배치해 주는 역할을 해요.

출처: 문서

본문

<script lang="ts">
  import { AspectRatio } from "bits-ui";
</script>
<AspectRatio.Root
  ratio={14 / 9}
  class="rounded-15px scale-[0.8] bg-transparent"
>
  <img
    src="/abstract.png"
    alt="an abstract painting"
    class="h-full w-full rounded-[15px] object-cover"
  />
</AspectRatio.Root>

구조(Architecture)

  • Root: 화면 비율 계산 로직을 담고 있는 루트 컴포넌트예요.

구조(Structure)

Aspect Ratio 컴포넌트가 코드에서 어떤 구조로 이루어져 있는지 한눈에 보여드릴게요.

<script lang="ts">
  import { AspectRatio } from "bits-ui";
</script>
<AspectRatio.Root />

재사용 컴포넌트(Reusable Component)

앱 전체에서 AspectRatio 컴포넌트를 많이 쓸 예정이라면, AspectRatio.Root와 그 안에 렌더링할 요소들을 하나로 묶은 재사용 컴포넌트를 만들어 두면 편리해요. 아래 예시는 src prop을 받아서 그 값을 가진 img 요소를 렌더링하는 재사용 MyAspectRatio 컴포넌트를 만드는 모습이에요.

MyAspectRatio.svelte

<script lang="ts">
  import { AspectRatio, type WithoutChildrenOrChild } from "bits-ui";
  let {
    src,
    alt,
    ref = $bindable(null),
    imageRef = $bindable(null),
    ...restProps
  }: WithoutChildrenOrChild<AspectRatio.RootProps> & {
    src: string;
    alt: string;
    imageRef?: HTMLImageElement | null;
  } = $props();
</script>
<AspectRatio.Root {...restProps} bind:ref>
  <img {src} {alt} bind:this={imageRef} />
</AspectRatio.Root>

그러면 앱에서는 이렇게 MyAspectRatio 컴포넌트를 사용할 수 있어요.

+page.svelte

<script lang="ts">
  import MyAspectRatio from "$lib/components/MyAspectRatio.svelte";
</script>
<MyAspectRatio
  src="https://example.com/image.jpg"
  alt="an abstract painting"
  ratio={4 / 3}
/>

커스텀 비율(Custom Ratio)

ratio prop으로 이미지의 화면 비율을 원하는 값으로 설정할 수 있어요.

<AspectRatio.Root ratio={16 / 9}>
  <!-- ... -->
</AspectRatio.Root>

API 참조(API Reference)

AspectRatio.Root

화면 비율 컴포넌트예요.

Property Type Description Details
ratio number The desired aspect ratio.Default: 1
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-aspect-ratio-root '' Present on the root element.

더 알아보기 (Learn more)

화면 비율을 유지하면서 동그랗게 잘라 프로필 이미지를 만들고 싶다면 아바타(Avatar) 컴포넌트가 더 어울려요. 이미지가 로딩되는 상태까지 깔끔하게 처리하고 싶다면 함께 살펴보세요.