解决 Next.js 图片比例警告:next/image 的正确使用方式
HappyApril 14, 2025
问题描述
使用 Next.js 的 next/image 组件时,控制台出现以下警告:
Image with src "/images/[image-file-name-1010x554.webp]" has either width or height modified, but not the other. If you use CSS to change the size of your image, also include the styles 'width: "auto"' or 'height: "auto"' to maintain the aspect ratio.
警告的意思是说:
- 你只修改了图片的 width 或 height 中的一个属性,但没有同时调整另一个
- 这样会导致图片失去原始比例(变形/拉伸)
- 建议如果你用 CSS 调整图片尺寸,应该加上 width: "auto" 或 height: "auto" 来保持比例
原始问题代码
<Image
className='mx-auto hover:opacity-80'
src='/images/banner.png'
width={180}
height={48}
priority
/>
其实在这里我们都设置了宽和高但是依然触发了这个警告,原因是因为我们的宽和高的比例和图片比例不同。
解决方案
通过 CSS 显式指定 width 或 height 为 auto 来保持图片比例:
<Image
className='mx-auto hover:opacity-80'
src='/images/banner.png'
alt='网站横幅'
width={180}
height={48}
style={{
width: '100%',
height: 'auto', // 保持原始比例
}}
priority
/>
备选方案(Next.js 12 及更早版本)
对于老版本 Next.js,可以使用 layout="responsive" 属性:
<Image
className='mx-auto hover:opacity-80'
src='/images/banner.png'
alt='网站横幅'
width={180}
height={48}
layout='responsive' // 响应式布局
priority
/>
注意:Next.js 13+ 版本已弃用 layout
属性,推荐使用 style
或 className
进行样式控制