いつもwidthとheightを指定してImageコンポーネントを使用していたのですが、ピクセル指定ではなく幅いっぱいに広げたい時があり、やり方を調べました。
バーションなどによっても違うみたいですが、今の私の環境 (Next.js 14.1.4) での指定の仕方を記録しておきます。
tailwindCSSを使用しています。
結論
<div className="w-full">
<Image alt="hoge" src="/hoge/hoge.png" fill className="!relative" />
</div>
Imageコンポーネントの親要素で希望の幅を指定し、Imageコンポーネント自体にrelativeを充ててimportantにし、fillをtrueにすると完成です。
width/heightは基本的に必須のPropsですが、fillを指定したらなくても大丈夫のようです。
公式サイト確認する
以下、公式サイトのfillの説明です。
A boolean that causes the image to fill the parent element, which is useful when the width and height are unknown.
The parent element must assign position: "relative", position: "fixed", or position: "absolute" style.
By default, the img element will automatically be assigned the position: "absolute" style.
If no styles are applied to the image, the image will stretch to fit the container. You may prefer to set object-fit: "contain" for an image which is letterboxed to fit the container and preserve aspect ratio.
Alternatively, object-fit: "cover" will cause the image to fill the entire container and be cropped to preserve aspect ratio. For this to look correct, the overflow: "hidden" style should be assigned to the parent element.
「親要素を画像で埋めるブール値」だそうですので、親要素で幅指定してfillをtrueにしたらOKということみたいです。
また、「position: "absolute"」がimageコンポーネント自体にデフォルトで割り当てられているので、relativeをimportantで指定しないと意図しないところに画像が表示されてしまいます。
公式サイト読むの少し抵抗ありますが勇気を出して(翻訳して)読むと、意外と理解できます。
わからなかったらまず公式の癖つけたいです。