프론트엔드/Next.js

[Next.js] <Image/> 태그 사용방법 (이미지 원본 비율 유지하기 & 부모 요소 너비 꽉 채우기)

순코딩 2025. 4. 21. 15:00

코드

1. 이미지 원본 비율 유지하기

<PreviewImage src={el.imgSrc} alt="" width={200} height={200} />


const PreviewImage = styled(Image)`
  width: auto;
  height: auto;
`;

 

2. 부모 요소 너비만큼 채우기

<PreviewImage>
    <PreviewImage src={el.imgSrc} alt="" width={200} height={200} />
<PreviewImage/>




const PreviewContainer = styled(Box)`
  width: 300px;
  min-height:300px;
`;


const PreviewImage = styled(Image)`
  width: auto;
  height: auto;
  object-fit:contain; // 이미지 비율을 유지하기
  object-fit:cover; // 부모 요소 너비 꽉 채우고 넘치는 부분을 잘라내기
`;

 

 

참고자료

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

 

Components: Image | Next.js

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

nextjs.org