728x90

들어가며

Next.js의 next/image 컴퍼넌트는 굉장히 많은 역할을 해줍니다.  보통  Image를 사용할 떄는 아래와 같이 width, height을지정해주고 사용합니다. 이후 화면이나 외부 컨테이너가 작아짐에 따라서 이미지의 크기가 줄어듭니다.

import Image from 'next/image'
 
export default function Page() {
  return (
    <Image
      src="/profile.png"
      width={500}
      height={500}
      alt="Picture of the author"
    />
  )
}

 

하지만 이번 프로젝트에서는 이미지의 크기가 외부 영역에 영향을 받게 되었습니다. 

이때 사용할 수 있는 속성이 fill입니다.

 

Next/Image Fill속성 사용하기

정확하게 크기를 정의할 수는 없지만, 외부 영역 기준으로 가득차게 할 때는 fill을 사용할 수 있습니다.

공식문서  Responsive Image with Fill  

import Image from 'next/image'
 
export default function Page({ photoUrl }) {
  return (
    <div style={{ position: 'relative', width: '300px', height: '500px' }}>
      <Image
        src={photoUrl}
        alt="Picture of the author"
        sizes="300px"
        fill
        style={{
          objectFit: 'contain',
        }}
      />
    </div>
  )
}

 

예시를 봤을 때, fill를 사용할때는  3가지를 고려해야 합니다.

1. fill을 사용하면 Image컴퍼넌트가 absolute 포지션이기에 외부가 absolute, fiexd, relative중 하나여야 한다.

// 공식문서 내부의 : packages\next\src\client\image-component.tsx

	if (img.parentElement) {
          const { position } = window.getComputedStyle(img.parentElement)
          const valid = ['absolute', 'fixed', 'relative']
          if (!valid.includes(position)) {
            warnOnce(
              `Image with src "${origSrc}" has "fill" and parent element with invalid "position". Provided "${position}" should be one of ${valid
                .map(String)
                .join(',')}.`
            )
          }
        }

 

2. sizes를 사용하여 최적화를 해야한다.

(사용하지 않으면 아래의 경고 문구가 나옵니다.) 

                `Image with src "${origSrc}" has "fill" but is missing "sizes" prop. Please add it to improve page performance. Read more: https://nextjs.org/docs/api-reference/next/image#sizes`
 

 

이전 포스트를 통해서 next.js의 image 가 html의 img태그를 사용하고 있음을 알 수 있었고, srcset과 preload를 사용하여 최적화를 시도하고 있음을 확인했습니다.

mdn 에서 img태그의 sizes를 확인해보면 뷰포인트 크기를 활용하여 반응형으로 소스크기를 적용할 수 있습니다.

width가 정해지지 않은 경우에는 sizes옵션을 주어서 viewport에 따라서 소스의 크기를 결정할 수 있고, 최적화가 가능합니다. 

 

저는 화면이 1000px보다 작은 경우에는 400px, 클 경우 200px로 설정하였습니다.

	 <Image
          src={src}
          alt={alt}
          fill
          sizes="(max-width: 1000px) 400px, 200px"
  	  />

 

 

3. style에서 objectFit 속성 사용

fill을 사용하더라도 이미지의 비율이 유지되기를 생각할 것입니다. 이떄 사용할 수 있는 것이 objectFit이고 이는 12버전까지 next/image에 포함되어  있는 기능이었습니다.

 

 

하지만 현재에는 deprecated 됐으며 공식문서 예시와 같이 css에서 관리해야 합니다.

 

https://nextjs.org/docs/pages/api-reference/components/image-legacy#comparison

 

 

next.js에서  style이나 className등을 사용한 css의 영역을 지지하여  관심사가 분리되었기 때문입니다.

 

 

 

참고 문헌

공식 문서 Image 컴퍼넌트 : https://nextjs.org/docs/app/api-reference/components/image

 

Components: <Image> | Next.js

Optimize Images in your Next.js Application using the built-in `next/image` Component.

nextjs.org

 

 

mdn img태그 

https://developer.mozilla.org/ko/docs/Web/HTML/Element/img

 

<img>: 이미지 삽입 요소 - HTML: Hypertext Markup Language | MDN

HTML <img> 요소는 문서에 이미지를 넣습니다.

developer.mozilla.org

https://nextjs.org/docs/pages/api-reference/components/image-legacy

 

Components: <Image> (Legacy) | Next.js

Backwards compatible Image Optimization with the Legacy Image component.

nextjs.org

 

+ Recent posts