You might have come across situations where you need to set the image height to the height of the container. You might not know the dimensions of the image before hand and also, the height of the container may vary dynamically.
In this article, we will see how you can fit the image to the container height while using Next.js image.
Create a custom image component:
1"use client"23import Image from "next/image"45export default function ImageComponent({6 src,7 alt,8}: {9 src: string,10 alt: string,11}) {12 return <Image src={src} alt={alt} fill style={{ objectFit: "contain" }} />13}
- The
fill
property causes the image to fill the parent element. - The style property
objectFit:"contain"
makes the image to keep the aspect ratio.
Now use the ImageComponent
as shown below.
1import ImageComponent from "./components/ImageComponent"23export default function Home(props) {4 return (5 <div style={{ height: "300px", position: "relative" }}>6 <ImageComponent7 src="https://placehold.co/600x400.png?text=Hello\nWorld"8 alt="image"9 />10 </div>11 )12}
Note that you need to provide the style position: "relative"
to the wrapping element as the display attribute
of the image will be set to absolute
when we pass fill
as true
.
If you want the image to occupy both width and height and maintain aspect ratio, then you can give
objectFit:"cover"
. In this case entire image may not be displayed.
Do follow me on twitter where I post developer insights more often!
Leave a Comment