0

I'm presenting images using tag in NextJs application. I would like to display the images responsively, without causing whitespace horizontally. See this image for example enter image description here

You can see that there is a lot of whitespace as I'm hardcoding height and width of my image. My code is

                  <Image
                src={urlFor(node).url()}
                layout={"responsive"}
              width={600}
                height={400}
                alt={"content image"}
              />

Is there any way to display responsive images without such white spaces?

Sachin Titus
  • 1,960
  • 3
  • 23
  • 41

1 Answers1

0

The next/image component in responsive layout work in the following way make sure you don't have a wrapper component (or HTML element) with size limitation (width, height, max-width, ...) around the component (Image)

NOTE I'm using tailwindcss for important aspect properties to express the behavior, Next uses direct style on its element.

<div class="block relative overflow-hidden">
  <div class="block" style="padding-bottom: var(--padding-bottom)"></div>
  <img 
    class="absolute top-0 right-0 left-0 bottom-0 
           max-h-full max-w-full min-h-full min-w-full
           h-0 w-0" 
    src="..." 
    ...
  >
</div>

Where --padding-bottom is (height / width * 100)% grabbed from props.

So if your Image can not change the layout width. The image just tries to fill all the given space. inner div tries to keep the aspect ratio clean and precise. outer div is responsible for image space (size) in the output view.

In version 10.1 of Next.js, there has been added a feature layout=" responsive" to make the image 100% of its container

amirhe
  • 2,186
  • 1
  • 13
  • 27
  • Is there any way to set the actual resolution of the image as height and width of responsive? – Sachin Titus Oct 19 '21 at 14:24
  • if you mean to make the image as big as its intrinsic size, you can pass the same height and width of the image to style prop of a simple wraonpper div around Image – amirhe Oct 19 '21 at 14:34
  • Is there any way to get the width and height of the image? Because different sizes of images get posted every day – Sachin Titus Oct 19 '21 at 15:33
  • There are ways to get the intrinsic size of the image, but they all need the image to be fully loaded, and it will cause FOIT in your design if you want to wait and add the image later, also width and height are for accessibility and performance too. I guess there is problem with your style or wrapper component, try to inspect dem and see what cause size issue. – amirhe Oct 19 '21 at 15:41