Lately, I've been exclusively using Next/Image due to Vercel's powerful image optimization service. While I've successfully replaced background-image
with DIVs and z-index
in most scenarios, I'm facing challenges in achieving two specific goals: 1.) Making a background image fill the entire viewport, and 2.) Preventing it from resizing when the window is resized.
For reference, here's an example I'm trying to replicate:
Link
Here's how I'm attempting to achieve this in NextJS:
<div className="overflow-hidden">
<Image
src={coverImg}
alt="Cover Image"
className="" fill
/>
</div>
I'm also incorporating TailwindCSS into my project. Any assistance would be greatly appreciated!
UPDATE: Here's the approach I've tried:
// @/components/Layout/index.js
import React from 'react'
import Head from 'next/head'
import Image from 'next/image';
import coverImg from '@/img/cover.jpg';
export default function Layout({ pageTitle, children }) {
let titleConcat = "Jay Simons";
if (pageTitle) titleConcat += " | " + pageTitle;
return (
<>
<Head>
<title>{titleConcat}</title>
</Head>
<main className="h-screen text-white">
<div className="flex fixed top-0 right-0 bottom-0 left-0" style={{ zIndex: -1 }}>
<div className="flex shrink-0">
<Image
src={coverImg}
alt="Cover Image"
className="mx-auto min-[1920px]:w-[100vw]"
width={1920}
height={1080}
/>
</div>
</div>
{children}
</main>
</>
)
}
Additionally,
// @/pages/index.js
import React from 'react'
import Image from 'next/image';
import Layout from '@/components/Layout'
import coverImg from '@/img/cover.jpg';
export default function HomePage() {
return (
<Layout>
<div className="flex h-screen">
<div className="w-[300px] bg-bg1">
sidebar
</div>
<div className="flex">
content
</div>
</div>
</Layout>
)
}
You can view the deployed version on Vercel here.
The issue I'm currently facing is that the image loses its centering when I resize the window. I have also attempted using the object-cover
class without success.