接下来 JS 图像居中,同时屏幕尺寸增加

SIL*_*ENT 4 html javascript css next.js nextjs-image

我在使用 NextJS 的组件时遇到了困难Image。我想设置一个横幅图像。无论屏幕尺寸如何,该图像在任何时候都只能覆盖屏幕上的一定空间。max-height: 30vh我已经让它主要与和的组合一起使用overflow: 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>
);
Run Code Online (Sandbox Code Playgroud)

El *_*per 12

如果您想根据需要对齐图像,您应该使用layout="fill"例如。objectFit="cover"

下一页/图像 API 参考

填充时,图像会将宽度和高度拉伸到父元素的尺寸,通常与 object-fit 配对。

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

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

这应该可以解决问题:

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>
);
Run Code Online (Sandbox Code Playgroud)

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