'Next.JS Image `layout='fill'` is broken

When using the Next.js image component, the docs claim that: "When fill, the image will stretch both width and height to the dimensions of the parent element, usually paired with object-fit."

However, this is not what's happening. What it actually does is fill the image to take up the entire screen in a fixed position that doesn't respect scrolling. I've tried each object-fit value possible for the img and none has worked.

To reproduce, make a new next project and put an image in your public folder. Do this:

export default function Home() {
  return (
    <div>
      <div style={{width: '100px', height: '100px'}}>
        <Image src={"/i.png"} layout='fill'/>
      </div>
    </div>
  )
}

Image will take up the entire screen. You can try styling the Image component but I haven't found a way to make it work.

Does anyone know how to fix this, or why it's happening?



Solution 1:[1]

The wrapping div should have position: relative:

export default function Home() {
  return (
    <div>
      <div style={{width: '100px', height: '100px', position: 'relative'}}>
        <Image src={"/i.png"} layout='fill'/>
      </div>
    </div>
  )
}

This is a consequence of how position: absolute works. It's containing block will be the nearest ancestor element that has any position value but static (the initial value).

Solution 2:[2]

You need to use position: relative for parent element.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dinesh Kumar