3
0

【Next.js エラー対応】"Image with src "/images/[image-file-name.png]" has either width or height modified, but not the other..."

Posted at

Next.js の next/image で画像の縦横比を設定しろと怒られた場合の対処法。
(公式マニュアルをちゃんと読んでおけば遭遇しないやつ)

エラーメッセージ

"Image with src "/images/[image-file-name.png]" 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."

直訳:「[画像名]は幅か高さのどちらかが変更されていますが、もう一方は変更されていません。CSSを使って画像のサイズを変更する場合は、縦横比を維持するために「width: "auto"」または「height: "auto"」スタイルも含めてください。」

元のコード

<Image
    className='mx-auto hover:opacity-80'
    src='/images/bannd'
    width={180}
    height={48}
    priority
/>

解決策

CSS で画像の width か height のいずれかに auto を指定し、縦横比を維持してやることで解決。

<Image
    className='mx-auto hover:opacity-80'
    src='/images/banner.png'
    alt='d'
    width={180}
    height={48}
    style={{ // 追加
        width: '100%',
        height: 'auto',
    }}
    priority
/>

ボツ案

Next.js 12 以前の方法:
layout="responsive" を追加。これにより、画像は親要素に対してレスポンシブになり、指定した幅と高さを基にアスペクト比が維持される。

<Image
    className='mx-auto hover:opacity-80'
    src='/images/banner.png'
    alt='代替テキスト'
    width={180}
    height={48}
    layout='responsive' // 追加
    priority
/>
3
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0