Utilizing next/image as a backgroundImage in a div container

Currently, I am working with nextjs and I am trying to set a background Image for a specific div using next/image. Most of the sources I found only explain how to implement full screen background images with next/image, not for a single div. I stumbled upon this resource https://uharston.medium.com/next-js-image-optimization-on-background-images-65de18ea03f5, but it focuses on full-screen backgrounds. Although I can use a normal background image, it lacks the optimization benefits of next/image.

The code snippet I've attempted is as follows:

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 am aiming for a design like this: https://i.sstatic.net/Y1bZX.png

However, my current outcome resembles this: https://i.sstatic.net/MJsni.png

My goal is to have the text "Welcome Home and Tom Text" displayed over the image. Any assistance in achieving this would be greatly appreciated.

Answer №1

To implement the image as the background of the div, you can use the following code:

<div style={{
  height: "600px", 
  position: "relative", 
  backgroundImage: `url(${imgPath})`,
  backgroundSize: "cover", 
  backgroundPosition: "center"
}}>

Alternatively, utilize next/Image component for the same purpose:

<div style={{
  height: "600px", 
  position: "relative"
}}>
  <Image
    alt="main-image"
    src={imgPath}
    fill
    quality={100}
  />
  <div style={{
    position: "absolute",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    color: "white",
    textAlign: "center"
  }}>
    <h3>Welcome to Our Home</h3>
    <h4>John Doe</h4>
  </div>
</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

Implementing pagination and filtering in a single MERN controller

Is it possible to implement pagination and filtering in the same controller? Filter service:- const filterPosts = async (filterData, token) => { const config = { headers: { Authorization: `Bearer ${token}`, }, data: { ...

What is the best way to increase padding in a Vuetify view element?

I have been attempting to increase the padding of my view by utilizing the "px-5" class on the container within the view. However, I am struggling to achieve the desired amount of padding. What I am aiming for is padding similar to what is shown in this sc ...

When my screen measures 1700px wide, a width of 100% in CSS appears significantly narrower than a width of 500px

Currently, I am working on designing a responsive layout for a 3D globe. The code snippet that stores the structure is as follows: <div class="text-center main"> <canvas id='globe' width='100%' height='100%'> ...

Can Material UI be defined as a peerDependency while maintaining its types as a DevDependency?

Is there a way to set Material UI as a peerDependency while keeping its types as DevDependency? I'm currently working on a component library using React + Typescript, with components based on Material UI and Rollup as the module bundler. For example ...

Having encountered peculiar behavior while trying to install npm

When attempting to install npm packages in my React Native project and running npm install, I am encountering an issue where the packages are installed with random strings appended. This unexpected behavior is causing my project to break. For example, I ...

Why is the div element within the container not automatically occupying 12 columns, but rather only 1?

I'm struggling to comprehend the bootstrap grid system, as explained in Murach's .Net book. Please take the time to read through the entire post. I am aware of the solution (<div class="col-lg-12">Col x</div> works), but I am curious ...

Each keystroke is saved individually in an array, thanks to React, instead of storing the entire text

Hey everyone, I have a task to develop a full-stack web application that allows users to create meals with ingredients, preparation details, and cooking time. I am using MongoDB, Node.js, Express, and React for this project. Everything works fine when test ...

We regret to inform you that an application error has occurred: a client-side exception has been encountered. Please refer to the browser

Fix for Nextjs Blog App Error If you encounter the following error message: Application error: a client-side exception has occurred (see the browser console for more information). when trying to create a post on AWS Amplify console and DynamoDB is failing ...

What is the best way to enhance specific sections of Django content by incorporating <span> tags, while maintaining the original paragraph text format?

I am currently in the process of trying to showcase a paragraph of text (content) from django. However, my aim is to incorporate <span class="modify"> into particular words that match pre-defined words located within a referenceList within the paragr ...

Update the URL for the Swagger 2.0 documentation path

This is how I set up swagger : const openapi = Openapi.initialize({ paths: openApiPaths, app, apiDoc, }); const openApiSpec = openapi.apiDoc; console.log(openApiSpec); app.use(swaggerUI(openApiSpec)); How do I update the base path ...

What is the best way to ensure that all elements inside a Grid item extend to the bottom, except for the text?

I currently have four columns within a Grid container, each structured as follows: <Grid item> <Typography>Big Title 1</Typography> <Card className={classes.stretchMe}> <CardContent> ...

What is the best way to expand the width of a table cell in a React + Material project?

Currently, I am utilizing material UI in conjunction with React to display my data in a table format. Within the table, there are specific titles such as "GENERAL_INFORMATION" and "INFORMATION" that I intend to center align. However, I have encountered an ...

Tips for maintaining consistent webpage layout across various screen sizes

Although this method may seem outdated, I have always been intrigued by how it was accomplished. In the past, before websites became responsive, pages would simply shrink down to fit on mobile devices without adjusting their appearance. How was this achie ...

Interactive Bootstrap 4 button embedded within a sleek card component, complete with a dynamic click event

I am trying to create a basic card using bootstrap 4 with the following HTML code. My goal is to change the style of the card when it is clicked, but not when the buttons inside the card are clicked. Currently, clicking on the test1 button triggers both ...

The combination of TypeScript 2.6 and material-ui 1.0.0-beta.24's withStyles with react-router withRouter is resulting in the error message: "Property 'classes' is missing in type."

Using the high order components withStyles and withRouter together has been a smooth process so far. However, after upgrading to the latest versions of these components, an error occurred. Learn more about higher-order components List of packages used: ...

Tips for modifying the response of an ExpressJS server following a timeout on a POST request

Currently, I'm in the process of creating a server using Node.js and ExpressJS. The issue arises when the client sends a POST request instructing the server to control an external device's movement either up or down. My goal is for the server t ...

Stop receiving updates from an Observable generated by the of method

After I finish creating an observable, I make sure to unsubscribe from it immediately. const data$ = this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1').subscribe(res => { console.log('live', res); data$.unsubscr ...

Tips for utilizing material-ui breakpoint rule within external styles?

I am facing an issue while trying to add a breakpoint rule to external styles for my component. The documentation I referred to explains how to do it, but it assumes the code and styles are in one file. The component in question is a table row: import Re ...

A step-by-step guide on making an animation series with html and css keyframes

I've been working on creating a captivating animation using HTML and CSS keyframes, but I seem to have hit a roadblock. Despite trying different rotations and transforms, I can't seem to achieve the desired effect depicted in the image below. The ...

sketch a portion of a picture on a canvas

My challenge involves a canvas with dimensions of 400 by 400, and an image sized at 3392 by 232. I am looking to crop the first 400 pixels of this image and display them within the canvas. How can I achieve this task? $(document).ready(function () { v ...