Next JS responsive image with custom size

19.8k Views Asked by At

I'm trying to implement an image grid like in AirBnB with Next JS. so I'm Using Next Image with responsive layout. but i wanted to make the image square. meaning the height and width should be the same. but when in responsive layout the image is set with it's original size. i even tried to make the object fit cover.

<div className="relative flex flex-col -z-10">
      <Image
        src={"/profile.webp"}
        layout="responsive"
        objectFit="cover"
        height={100}
        width={100}
      />
    </div> 

how can i achieve that?

3

There are 3 best solutions below

5
On BEST ANSWER

this is the code that worked for me, if anyone looks for this maybe it will be useful.

      <div className="w-full relative pt-[100%]">
        <Image
          src="/profile.webp"
          alt="profile"
          objectFit="cover"
          fill
          className="w-full h-full top-0 left-0 object-cover rounded-2xl"
        />
      </div>
0
On

Use this method for the NextJS 13 image: Enable experimental feature image by adding this to the next.config.js

module.exports = {
experimental: {
    images: {
        allowFutureImage: true
    }
  },
}

By enabling this, you can now add style or classes directly to the image components.

<Image
    src={data.image}
    width="0"
    height="0"
    sizes="100vw"
    className="w-full h-auto"
/>
0
On

with MUI

       <Box
          sx={{
            width: { md: '161px', xs: '120px' },
            height: { md: '28px', xs: '21px' },
            position: 'relative'
          }}>
          <Image
            src={'/assets/logo.svg'}
            alt='logo'
            layout='fill'
            objectFit='cover'
          />
        </Box>