I'm unable to create a fixed background image (parallex effect) using Tailwind CSS + Next.js Image.
You can see it in action on this Template Monster theme.
This is the code I have tried:
<section className="stats w-full h-48 relative">
<div className="absolute top-0 right-0 bottom-0 left-0 object-cover bg-cover">
<Image
layout='fill'
src={data.backgroundImageUrl}
/>
</div>
<div className="relative z-10 flex flex-col items-center">
<div>Stat 1</div>
<div>Stat 2</div>
<div>Stat 3</div>
<div>Stat 4</div>
</div>
</section>
And it does not work. The image attaches to the section and there is no parallax effect.
I can replace it with:
<div className="aboslute top-0 right-0 bottom-0 left-0 object-cover bg-cover"
style={{
backgroundImage: `url(${data.backgroundImageUrl})`
}}
/>
And it works. But then it does not optimize the image and my SEO score drops in lighthouse.
How can I use next/image alongside TailwindCSS for parallax effect of section backgrounds?
You can try something like this https://stackblitz.com/edit/nextjs-aye7nj?file=pages%2Findex.js Create wrapper with clipPath property and wrapper with fixed position.
<div
style={{
position: 'relative',
height: '60vh',
width: '100%',
clipPath: 'inset(0 0 0 0)',
}}
>
<div
style={{
position: 'fixed',
height: '100%',
width: '100%',
left: '0',
top: '0',
}}
>
<Image
src="https://images.unsplash.com/photo-1630496128261-27ce4ab6ad76?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2070&q=80"
layout="fill"
objectFit="cover"
sizes="100vw"
/>
</div>
</div>