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

