Next JS image centering while screen size increases

Viewed 6446

I've been having a tough time working with NextJS's Image component. I want to setup a banner image. This image must only cover a certain amount of space on the screen at any time, regardless of screen size. I've gotten this to mostly work with the combination of max-height: 30vh and overflow: hidden. However, I can't seem to get the image to center while the screen size changes. It should vary from seeing the entire image to focusing on the bed. Instead, its focusing on the pic's ceiling.

Live sample: https://codesandbox.io/s/nextjs-image-layout-lc7vb?file=/src/pages/index.tsx

const Index = (props: IBlogGalleryProps) => (
  <Main
    ...
  >
    <div className="w-full overflow-hidden" style={{ maxHeight: '30vh' }}>
      <Image width="300" height="200" layout="responsive" src="https://images.unsplash.com/photo-1519494080410-f9aa76cb4283?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1920&q=80" />
    </div>
    ...
  </Main>
);
2 Answers

If you want to align the image according to your needs, you should use layout="fill" with eg. objectFit="cover".

next/image API Reference

When fill, the image will stretch both width and height to the dimensions of the parent element, usually paired with object-fit.

For this to work, the container needs a height and position: relative.

You can also set objectPosition if you don't want the CSS's default object-position: 50% 50%.

This should do the trick:

const Index = (props: IBlogGalleryProps) => (
  <Main
    ...
  >
    <div className="w-full overflow-hidden relative" style={{ height: '30vh' }}>
        <Image layout="fill" objectFit="cover" src="https://images.unsplash.com/photo-1519494080410-f9aa76cb4283?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1920&q=80" />
    </div>
    ...
  </Main>
);

Here is an working example: https://codesandbox.io/s/nextjs-image-layout-forked-82op5?file=/src/pages/index.tsx

<div
     style="
            height: 30vh;
            width: 100%;
            max-width: 800px;
            position: relative;
            background-image: url('/imagelink/image.jpg');
            background-position: center center;
            background-size: cover;
            ">

</div>

you could use a div and set to it a background. What you call fixing on the bed are done with the background-position tag.

But you can also use object-fit and object-position for the <img/> tag. like this:

object-fit: cover;
object-position: center;

this will make you image always 100% width and height of the <img/> box size and also center it.

Related