Is there a way to superimpose text onto an image within a ReactJS/NextJS application?

I'm facing issues with applying CSS styles properly in my ReactJS/NextJS application. I am working on a component that displays an image with text overlaid on it. Despite testing the styles on w3schools, I cannot seem to get them to work correctly in my code. Attached are screenshots comparing my code to what was tested and how it appears on localhost:3000. The div tagged with imageContainer1 has a background-image set in the CSS file, but it doesn't display on the screen. Instead, the image displayed is from another div that includes inline styling (somewhere I can’t recall). Interestingly, when I try moving the styles from inline to style tags or the CSS file, they no longer apply consistently as before. This inconsistency in styling behavior confuses me.

My aim is to showcase an image spanning the full width of the viewport with text overlaying it. Any guidance on this issue would be highly appreciated.

https://i.sstatic.net/WMyxt.jpg https://i.sstatic.net/HhLav.png https://i.sstatic.net/3CCCc.png

import styles from './HomeContent.module.css'

const Home = () => {

return (
  <div className={styles.container}>
    <div className={styles.imageContainer1}></div>
    <p className={styles.text}>
        text
    </p>
 </div>
    
    
  )
}
export default Home


.imageContainer1 {
  background-image: url(../public/redtesla.jpg);
  height: 100%; 
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  max-width: max-content;
  /* position: relative;
  text-align: center;
  background-color: blue; */
}
.container {
  height: 100%;
  margin: 0;
}

.text{
  position: 'absolute';
  top: '25%';
  left: '10%';
  color: "red";
}

Answer №1

Are you still in need of a solution? In my experience with NextJs, here is what I usually do:

  1. Start by importing the Image Element from NextJs

    import Image from "next/image";

  2. Instead of using the width and height props, use the fill prop like this: fill={true}

  3. Then, set the position to relative and give a height to the text element that you want to display above the image.

  4. Make sure to align the content of that text element using align-content: center;

    If you require more information on Image props, you can visit this link

    'use client'

    import Image from "next/image" import {useEffect} from 'react' import img from './../../public/treeline.png' import img2 from './../../public/beach.png'

Here's an example implementation inside a function called Carousel:

  return (
    <>
    <div id="carouselExampleAutoplaying" className="carousel slide" data-bs-ride="carousel">
    <div className="carousel-inner">
      <div className="carousel-item active">
        <Image src={img} className="d-block w-100" fill={true}  objectFit="cover" alt="..."/>
        <h1 className={classes.h1}>Lorem Ipsum</h1>
      </div>
      <div className="carousel-item">
      <Image src={img2} className="d-block w-100" fill={true} objectFit="cover" alt="..."/>
        <h1 className={classes.h1}>Lorem Ipsum </h1>
      </div>
      <div className="carousel-item">
      <Image src={img} className="d-block w-100" fill={true} objectFit="cover" alt="..."/>
        <h1 className={classes.h1}>Lorem Ipsum</h1>
      </div>
    </div>
    <button className="carousel-control-prev" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="prev">
      <span className="carousel-control-prev-icon" aria-hidden="true"></span>
      <span className="visually-hidden">Previous</span>
    </button>
    <button className="carousel-control-next" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="next">
      <span className="carousel-control-next-icon" aria-hidden="true"></span>
      <span className="visually-hidden">Next</span>
    </button>
  </div>
  </>
  );
}


.h1 {

position: relative;
height: 60vh;
align-content: center;
width: 70vw;
text-align: center;
margin-left: auto;
margin-right: auto;
color: white;

}

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

Encountering a 400 bad request error while trying to post data using

const fetch = require("node-fetch").default; let iApi = express.Router(); iApi.post("/update/:name/:value", async (req, res) => { const name = req.params["name"]; ...

Steps for swapping out the page loader with the company logo icon

Instead of using a generic gif loader, I am looking to display my company logo with some animation before the page loads. I currently have the page_loader div class with a loader.gif image, but I want to customize it using CSS for a more unique look. .pag ...

Is there a way to view an image before and after uploading it?

I am encountering an issue while attempting to display a preview of an image in a form. The HTML code involved is as follows: <form action="" method="post" enctype="multipart/form-data" name="personal_image" id="newHotnessForm"> <p><lab ...

"I encountered an error stating that res.json is not a function while trying to establish a connection between ReactJS

dataset.list.js import React, { Component } from "react"; import Datasets from "./data"; import axios from "axios"; class App extends Component { render() { return <Datasets datasets={this.state.datasets} />; } ...

Ensuring the presence of an attribute within an AngularJS Directive

Is it possible to determine if a specific attribute exists in a directive, ideally using isolate scope or the attributes object as a last resort? If we have a directive like this <project status></project>, I would like to display a status ico ...

Div over which scroll editing is performed

I want to develop a website where my title div remains fixed in one position as I scroll down. However, the issue arises when I set it to be fixed because my navigation button on the left disappears and I'm unsure how to keep it in place. // JavaSc ...

Mechanism for enhancing and modifying capabilities of an object through a design pattern

TL:DR design pattern for objects that temporarily modify each other in a game scenario. Functionality is added and then removed dynamically. As a database developer delving into front-end development, I am exploring new techniques to stay informed about v ...

Unexpected session error in NEXT.js app router with NextAuth: Session is not defined

I have implemented NextAuth with NEXT.js app router for authentication. The dashboard component is enclosed within an auth-guard that verifies whether the user is authenticated or not. Here is the code snippet for the auth-guard. export default function A ...

Is there a way to customize the background color of notistack in MUI v5?

The background color is currently set to white by default, but I am interested in changing it to a darker shade. In the mui v5 framework, dark mode can be enabled. While I have managed to change the error, info, and other variants, my main goal is to adj ...

"Get a glimpse of the brackets image with real-time live

I seem to be encountering a strange issue. I have double-checked the source code for my image, and when I view the page in Chrome without using Brackets, the image displays properly. However, when I use Brackets Live preview, the image does not show up i ...

I am interested in developing a JavaScript program that can calculate multiples of 0.10

I am looking to let users input values that are multiples of 0.10, such as - 0.10, 0.20, 0.30....1.00, 1.10, 1.20...1.90, and so on. When a user enters a value in the text box, I have been checking the following validation: amount % 0.10 == 0 Is this a ...

Issues with the collapsed navigation button not functioning properly on mobile devices with a Twitter Bootstrap layout

Encountering a problem where the collapsible navigation menu button is unresponsive on mobile browsers, while functioning correctly on desktop. I suspect it may be related to the parallax script installed by my client. Check out the page here: http://21 ...

Is there a way to decrease a field in a MongoDB database on a daily basis?

In the process of constructing an Angular2 application using MEAN stack architecture, I have a field called Remaining Days in my MongoDB database. I am interested in having this field automatically decrement by 1 each day. Do you know if this is possible ...

jQuery plugin is not effectively targeting the directive

Recently, I have been experimenting with using a sleek jQuery datepicker and decided to turn it into a directive for my angular app. The implementation of the directive is currently very straightforward: directive('datePicker', function() { ...

What could be causing the test runner to not find the plugin?

I've been experimenting with Test Runner for running tests and attempting to utilize the sendKeys function. Below is the test code, similar to what is provided on the website: import { sendKeys } from '@web/test-runner-commands'; it(' ...

"Enhancing selector parsing with the use of pseudo-elements for improved forgiveness

Is there a way to streamline CSS code using forgiving selectors like :is or :where with pseudo-elements in native CSS only? The documentation states that :is cannot be used with pseudo-elements, but I'm wondering if there's another solution that ...

I'm looking for recommendations on where to begin learning about JavaScript touch events for web development. Any suggestions?

Seeking guidance on creating image galleries and content sliders that work with both touch and mouse events. Where should I begin exploring touch event implementation? I'm having difficulty locating official documentation. Are there any jQuery-suppo ...

Trouble arises when trying to open a new window using the Angular 8 CDK

I am attempting to open my component in a new window, similar to this example: https://stackblitz.com/edit/angular-open-window However, when the window opens, my component is not displayed and I receive the following error in the console: Error: Must pro ...

Arranging React-Native FlatList in Alphabetical Order

This is the array containing data for flat list const DATA = [ { id: '1', name: 'Hamza Ahzam', phone: '03076232309', DOB: '05/07/96', }, { id: '2', name: 'Ahzam', phone: '031562 ...

For Flexbox front end design, the left side should be contained within a container while the right side should seamlessly stretch across the

https://i.sstatic.net/3RYY6.png I'm facing a challenge in designing a website with a unique layout that has left me puzzled. I've created a codepen example to showcase what I'm trying to achieve. Specifically, I need to implement a Hero Ba ...