1

So, I have a container div and an Image component in it. I want the image height be equal to the 100% of container height, and the width of container to be automatically decided based on the width of image according to its aspect ratio. When I use a normal img tag, this works without a problem, but in case of Next Image component, the image is left with a width of 0px. Because it wants me to define a fixed width for the container. ? How can I achieve what I want ?

What I'm doing is this:

for the div:

div {
   height: 50px;
   width: auto;
}

for the Image component:

<Image src="..." alt="..." layout="fill" />
noiseymur
  • 761
  • 2
  • 15

2 Answers2

1

As far as i know, Image in next js has one good great advantage, a lazyload preserving the space the image will use once is loaded without destroying the layout.

Now, that would be impossible if we dont pass the size of the image in advance.

Idk the limits of that. So, i am betting on this reason.

And thats the reason why i use a lot of img, instead of Image. But if you know the exact size... better use Image.

PS. Google developers participated on the feature development i just describe.

0

I think the most straight forward way is to just define the width of the div in ems or rems and define the same for the image as well so that it is the exact length and the parent element has a ratio with the image and the div itself. Have a great Day :)

theRish17
  • 9
  • 2
  • Thanks for taking your time to answer, but the problem is, image is fitted to the container. For example, image ratio is: 2:1. That means, if I set my container width to 150px and height to 50 px, image size will be 100px * 50px, leaving 50 px of container width empty. This would not be a problem if I knew the ratio of image, but in my case the image source is dynamic and ratio is not fixed, so I can't give same ratio to the container either; – noiseymur Jul 03 '21 at 08:43
  • The only loophole from there would be to hard code that image to be 150 px in width but it would look really hideous, but there is also a converse, if the design allows you to code the div itself to be 100px or around 20 ems, In my choice, that would be the way to go! Hope this helps a bit. – theRish17 Jul 03 '21 at 10:01