I’ve been using Next/Image for everything lately because of Vercel’s automatic image optimization service. I’ve been able to replace background-image
in pretty much every use-case by using DIVs in conjunction with z-index
, but I’ve had a heck of a time trying to get a background image to 1.) fill the entire viewport, and 2.) Not resize when the window shrinks.
Here’s an example of what I’m trying to duplicate:
https://watson-vcard.netlify.app/index-dark-particles2.html
Here’s an example of what I’m trying in NextJS:
<div className="overflow-hidden">
<Image
src={coverImg}
alt="Cover Image"
className="" fill
/>
</div>
I’m also using TailwindCSS. Thanks in advance for any help!
EDIT: Here’s what I ended up trying:
// @/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>
</>
)
}
And
// @/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>
)
}
And I deployed to Vercel here.
The problem I’m having now is the image doesn’t stay centered when I resize. I tried the object-cover
class too, to no avail.
2
Answers
Yes, the full-screen image is often achieved with
background-image
. But you can also achieve this with<img>
(in your case,<Image />
component from Next.js) by usingobject-fit
property:The
object-cover
is a Tailwind CSS utility class and it gives the image a similar effect to usingbackground-image
‘s withcover
andcenter
.Here is a background-image version:
Try using the following style for the image, I tried it on your website using dev tools and it works.
Further Suggestions:
content), you can better put the image tag inside the main content div
and make its position: relative; so that the image is
contained inside the main content div only (and not the entire page
while side content isn’t transparent)
Hence you main content div would be like the following.