Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use next/image for backgroundImage for a div block

I am using nextjs. I want use next/image for my background Image for a div. I saw several answers but everyone posting for full screen background image using next/image and not for a single div background image. I got this https://uharston.medium.com/next-js-image-optimization-on-background-images-65de18ea03f5. But its for full screen. I can use normal background Image but its not optimized like next/image.

Here’s the Code i tried:

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

I need like this,
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But I am getting this
enter image description here

I want the Welcome Home and Tom Text to be over the image. Please help me with some solutions.

>Solution :

You can set the image as background of the div like this :

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

Or with 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>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading