How to change height of NextJS Image tag according to screen width?

Viewed 2507

I am using next/image to render my image like this:

<Image 
 src={imageLink} 
 width="1920" 
 height="512" 
 alt="Hero Image" 
/>

This is fine for screen widths above 750px.

How to update the height to "612" when the user visits on mobile or tablet (below 750px screen width)?

3 Answers

Put Image inside div and put the following props on the Image:

<div className="div-class">
   <Image src={imageLink} layout="fill" objectFit="cover" />
</div>

The div in this example needs to have position: relative. Now you will be able to give this div any height/width you need with media queries

You create a css class (in your custom.css or anywhere)

Then you define props you need (height, styling etc)

@media (min-width: 576px) {
  .custom_class {
    max-width: 540px;
  }
}

@media (min-width: 768px) {
  .custom_class {
    max-width: 720px;
  }
}

@media (min-width: 992px) {
  .custom_class {
    max-width: 960px;
  }
}

@media (min-width: 1200px) {
  .custom_class {
    max-width: 1140px;
  }
}

put your Image inside div like this and you can change height and width now

 <div className='relative h-96 md:h-3/4'>
     <Image className='h-full sm:h-64' 
         src="/static/images/desktop/image-header.jpg" alt="sun" 
         layout='fill' objectFit='cover' width={400} height={350} />
 </div>
Related