【问题标题】:Resize a Next.js Image component inside a div在 div 中调整 Next.js Image 组件的大小
【发布时间】:2021-02-16 07:54:03
【问题描述】:

我尝试制作一个部分,该部分一方面包含一些文本,另一方面包含一个应该响应的图像(即,当窗口的大小也变得更小时,它会变得更小)。

使用简单的<img src="/myimage.extension" alt="describe my image" /> 确实可以完美运行。但是一旦我使用 Next.JS Image 组件(为了从它所做的优化中受益),它就会破坏响应能力。

确实,为了制作一种带有响应式图像的英雄部分,我得到了这段代码(工作得很好):

<>
<div className={"h-screen py-0 py-20 text-center bg-blue-100 text-dark-blue"}>
  <div
    className={"flex flex-col items-center justify-center h-full md:flex-row app-container md:justify-between"}>
    <div>
      <h1 className={"text-red-400"}>With the Image component</h1>
      <p>It doesn't resize on the size of the viewport</p>
    </div>
    <div className={"relative"}>
      <svg
        className={"absolute right-0 z-50 hidden w-1/2 sm:block"}
        css={css`top: 25px;left: 25px;`}
        xmlns="http://www.w3.org/2000/svg" viewBox="0 0 674 674"
      >
        <circle id="Ellipse_8" cx="337" cy="337" r="337" fill="#e23b58"/>
      </svg>
      <img
        src={"/image.jpg"}
        alt={"Some image description"}
      />
    </div>
  </div>
</div>
</>

然后,用Image 组件替换img 标记会破坏响应能力:图像永远不会变小。它保持它的大小。

<>
  <div className={"h-screen py-0 py-20 text-center bg-green-100 text-dark-blue"}>
    <div
      className={"flex flex-col items-center justify-center h-full md:flex-row app-container md:justify-between"}>
      <div>
        <h1 className={"text-red-400"}>With the Image component</h1>
        <p>It doesn't resize on the size of the viewport</p>
      </div>
      <div className={"relative"}>
        <svg
          className={"absolute right-0 z-50 hidden w-1/2 sm:block"}
          css={css`top: 25px;left: 25px;`}
          xmlns="http://www.w3.org/2000/svg" viewBox="0 0 674 674"
        >
          <circle id="Ellipse_8" cx="337" cy="337" r="337" fill="#e23b58"/>
        </svg>
        <Image
          src={"/image.jpg"}
          alt={"Some image description"}
          width={1103}
          height={628}
        />
      </div>
    </div>
  </div>
</>

您可以在此Sandbox 上看到正在发生的事情。我正在寻找一种方法,使我能够精确控制 Image 组件的定位方式。

【问题讨论】:

    标签: css reactjs next.js tailwind-css nextjs-image


    【解决方案1】:

    问题不在图像组件中。它与应用于 div 容器的样式有关。

    如果您从第 18-22 行的类中删除 items-center,您将看到图像正在调整大小:

    <div className={"flex flex-col items-center justify-center ...}>
    

    改为:

    <div className={"flex flex-col justify-center ...}>
    

    【讨论】:

    • 是的,你是对的。在垂直对齐上还会出现一个问题,可以使用更高的 flex 容器来处理。
    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多