How can I make a fixed background image with NextJS's Next/Image feature?

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.

Answer №1

Consider using this style for the image, I tested it on your website with dev tools and it was successful.

.bg-img{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    z-index: -1;
}

Additional Recommendations:

  • Instead of positioning the image to cover the entire page (including side content), you can place the image tag inside the main content div and set its position to relative; ensuring that the image is contained only within the main content div (without covering the entire page while side content remains opaque)

As a result, your main content div should look like this:

<div
  className="flex flex-col flex-grow"
  style={{
    position: "relative",
  }}
>
  <Image src={coverImg} alt="Cover Image" className="bg-img" />
  {/* Other main content divs children here */}
</div>

Answer №2

Achieving a full-screen image can be done using background-image, but it can also be accomplished with an <img> tag (such as the <Image /> component in Next.js) by utilizing the object-fit property:

<div className="overflow-hidden">
  <Image
    src={coverImg}
    alt="Cover Image"
    className="object-cover"
    fill
  />
</div>

The use of object-cover is a helpful Tailwind CSS utility class that provides a similar effect to using background-image with cover and center.

If you prefer a background-image approach, here's an example:

<div className='bg-[url("/cover-img.jpg")] absolute left-0 top-0 h-screen w-screen bg-cover bg-center'>
  Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sequi
  dignissimos esse corrupti eaque, iusto, optio pariatur eos consectetur
  odio voluptas fugiat ad aperiam id rerum at quos dolores consequatur
  consequuntur.
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Check domains using Jquery, AJAX, and PHP

I'm currently developing a tool to check domain availability. Here is the PHP code I have so far: <?php $domain = $_GET["domname"]; function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); ...

Despite encountering an error in my terminal, my web application is still functioning properly

My code for the page is showing an error, particularly on the home route where I attempted to link another compose page The error message reads as follows: Server started on port 3000 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after t at new Node ...

How come the mongoose ref feature is not functioning properly for me when I attempt to reference objects from a different schema?

I'm having trouble accessing the attributes of a store's address, as I keep getting 'undefined'. It seems that the address is only an id, even though I set up a 'ref' in the address schema. What could be causing this issue? H ...

Space empty on the right side of a card within a container - Bootstrap 4

I've been working on creating a responsive card for different screen sizes, but I've encountered a problem. On mobile screens, there seems to be some unwanted blank space on the right side of the card. Is there a way to center this card on smalle ...

Is it possible to fire a Socket.io emit with a scroll event?

Can you trigger an emit on a gesture or scroll event, similar to how it works on a click event? I'm trying to create something like this: https://www.youtube.com/watch?time_continue=38&v=tPxjxS198vE Instead of relying on a click, I would like to ...

Error: Unable to call topFrame.window.changeSelectedBarStyle because it is not a valid function. What could be causing this

This function is called changeSelectedBarStyle: function changeSelectedBarStyle(tdId){ $("#menuTable td").each(function(index){ if(this.id == tdId){ $(this).removeClass("menuPanel"); $(this).addClass("menuPanelSelected" ...

What steps can I take to fix this issue in a React project using Material UI?

Encountering an error while attempting to webpack the application on Windows 10 x64. ERROR in ./node_modules/material-ui/styles/withStyles.js Module not found: Error: Can't resolve '@babel/runtime/core-js/map' Attempted to find a solution ...

Troubleshooting: jQuery Drop event is not triggering

I am attempting to transfer links (.link) from one div (.folder) to another, but the drop event is not triggering. To make all .link divs droppable areas, I have disabled the default behavior in the dragenter and dragover events. Here is the code snippet: ...

no visible text displayed within an input-label field

Currently, I have started working on a multi-step form that is designed to be very simple and clean. However, I am facing an issue where nothing is being displayed when I click on the next arrow. I am puzzled as to why it's not even displaying the te ...

Retrieve information according to the object ID with AngularJS UI-Router and $stateParams

I have a unique application that directs to a custom URL based on a specific employee ID parameter when an individual employee is clicked in a list. Upon clicking the employee, users are redirected to a detailed employee page with their ID property as a pa ...

A secondary operation is triggered in the simulated keyboard when the enter or space key is pressed, even when it is not warranted

In my HTML, I have created a simulated keyboard with buttons that correspond to characters. When you click on these buttons, the character is added to a text element on the screen. Additionally, you can use your physical keyboard to input characters in the ...

Can you share the method for concatenating an object at a specific index within an Array using JavaScript?

Currently, I have an array arr = [object1, object2, object3]. After removing the second index, the array now looks like arr = [object1, object3], and I am looking to add back the removed object2 at its original position in the array so that it becomes a ...

The issue here is that "onreadystatechange" in JS Ajax is not defined, even

For the past day, I've been struggling with this issue and going in circles. Any help would be much appreciated :-) Synopsis I'm facing a challenge with asynchronous AJAX calls to CGI using resolver and FQDN variables to obtain DNS resolution ...

What is the best way to transform parameters in axios requests into objects?

Within my ReactJs app, I have implemented the following code: axios .get(`/shipping/get-shipping-values`, { params: { products: [ { ...product, quantity, }, ], ...

Notify immediately if there is any clicking activity detected within a designated div container

I am looking to trigger an alert when a specific div is clicked. Here is the scenario: <div class="container"> <div class="header"> <h1>Headline<h1> </div> <div class="productbox"></div> </div> I have succ ...

How can I remove the back button that the Ionic framework adds when using $state.go('app.home') to navigate to a page?

I have an app with a sidebar menu. Currently, I am on the second page and I am calling a controller function that redirects me to the first page using: $state.go('app.home'); The issue I am facing is that on this page, a back button is displayed ...

What is the best way to make a Modal triggered by a loop embedded within a table function properly on mobile devices?

While the modal is functioning properly on desktop, it seems to be encountering issues on mobile devices. The modal appears behind the background and is confined by the boundaries of the table (tbody). Below is the code snippet for triggering the modal: ...

The issue arises with Material-UI Drawer where it fails to close and triggers a warning in Chrome about an unknown prop `onRequestChange` on the <div> element

I am facing an issue with the material-ui navbar in my project. There is a button on the left-hand side that triggers a left-hand drawer to open. However, I am experiencing trouble with the drawer not closing when I press the escape key or click on the ove ...

Preventing the use of double-click on Grooveshark

I am currently in the process of creating a webpage to serve as a jukebox for parties. My goal is to have the page load Grooveshark with a transparent overlay (or any other necessary method) that can prevent users from forcefully adding their song to the f ...

Incorporate an additional ring around the outer edge of the donut pie chart

I have been attempting to create a donut pie chart similar to the one shown below. The main challenge I am facing is with the outer strip. How can I achieve this effect? Your guidance in the right direction would be greatly appreciated. https://i.sstati ...