typescript 如何将next/image用于背景将image用于div块

r9f1avp5  于 2023-01-10  发布在  TypeScript
关注(0)|答案(1)|浏览(166)

我正在使用nextjs。我想使用next/image为我的背景图像为一个div。我看到了几个答案,但每个人都张贴全屏背景图像使用next/image,而不是为一个单一的div背景图像。我得到了这个https://uharston.medium.com/next-js-image-optimization-on-background-images-65de18ea03f5。但它为全屏。我可以使用正常的背景图像,但它没有优化像next/image。
下面是我尝试的代码:

import Image from 'next/image'

export default function Home() {

  const imgURL = "https://i.postimg.cc/kXb4L4hB/abstract-blur-empty-green-gradient-studio-well-use-as-backgroundwebsite-templateframebusiness-report.jpg"

  return (
    <div style={{ backgroundColor: "black", height: "100vh" }}>
      <h1 style={{ color: "white", textAlign: "center" }}>Home Page </h1>

      {/* Background Image */}
      <div style={{ height: "500px", position: "relative" }}>
        <Image
          alt="main"
          src={imgURL}
          fill
          style={{ objectFit: "cover", objectPosition: "center" }}
          quality={100}
        />
      </div>

      {/* Content should come over image */}
      <div style={{ display: "flex", alignItems: "center", flexDirection: "column" }}>
        <h3 style={{ color: "white" }}>Welcome Home</h3>
        <h4 style={{ color: "white" }}>Tom</h4>
      </div>

    </div>
  )
}

我需要这样的x1c 0d1x
但我得到了这个

我希望Welcome Home and Tom Text是在图像。请帮助我一些解决方案。

wnavrhmk

wnavrhmk1#

您可以将图像设置为div的背景,如下所示:

<div style={{
  height: "500px", 
  position: "relative", 
  backgroundImage: `url(${imgURL})`,
  backgroundSize: "cover", 
  backgroundPosition: "center"
}}>

或者使用next/Image

<div style={{
  height: "500px", 
  position: "relative"
}}>
  <Image
    alt="main"
    src={imgURL}
    fill
    quality={100}
  />
  <div style={{
    position: "absolute",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    color: "white",
    textAlign: "center"
  }}>
    <h3>Welcome Home</h3>
    <h4>Tom</h4>
  </div>
</div>

相关问题