Next JS 图像居中,同时屏幕尺寸增加

Next JS image centering while screen size increases

我在使用 NextJS 的 Image 组件时遇到了困难。 我想设置横幅图片。无论屏幕尺寸如何,此图像在任何时候都只能覆盖屏幕上一定数量的 space。我已经让这个主要与 max-height: 30vhoverflow: hidden 的组合一起工作。但是,当屏幕尺寸发生变化时,我似乎无法让图像居中。它应该从看到整个图像到专注于床不等。相反,它专注于图片的天花板。

实时样本: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>
);
<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>

您可以使用 div 并为其设置背景。 你所谓的固定床是用background-position标签完成的。

但是您也可以使用 object-fitobject-position 作为 <img/> 标签。 像这样:

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

这将使您的图像始终是 <img/> 框大小的 100% 宽度和高度,并将其居中。

如果你想根据你的需要对齐图像,你应该使用 layout="fill" 与例如。 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.

为此,容器需要一个高度和 position: relative

如果您不想要 CSS 的默认值 object-position: 50% 50%,您也可以设置 objectPosition

这应该可以解决问题:

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>
);

这是一个工作示例:https://codesandbox.io/s/nextjs-image-layout-forked-82op5?file=/src/pages/index.tsx