How can I overlay text onto an image using ReactJS?

Today, I made the decision to venture into ReactJS and begin creating my own blog. One of the challenges I faced was trying to add text on an image in the header - only to find that the text kept sliding down. In order to ensure proper alignment, I needed the text position to be centered

[image] 1

Here is the code snippet:

Header.tsx

import React from "react";
import './header.scss'

const Header = () => {
  return (
    <header>
      <div className = "head-text">
        <div className = "head-image">
          <img src = {require ('../ images / Header.png')} alt = "Freedom Blog" />
        </div>
          <h3> Welcome to my Blog </h3>
          <p> FREEEEDOM </p>
      </div>
    </header>
  )
}


export default Header;

Main App file:

import React from 'react';
import Header from './components/Header';
import './index.scss'

const App = () => {
  return (
    <>
      <Header />
    </>
  );
}

export default App;

The CSS files are currently empty, so they have not been included.

Answer №1

To overlay text on an image using CSS absolute positioning, you can follow these steps:

Learn more about it here

Add a CSS class to the text you want to display on the image, like this:

const Header = () => {
  return (
    <header>
      <div className = "head-text">
        <div className = "head-image">
          <img src = {require ('../images/Header.png')} alt = "Freedom Blog" />
        </div>
          <div class='text-on-image'>
             <h3> Welcome to my Blog </h3>
             <p> FREEEEDOM </p>
          </div>
      </div>
    </header>
  )
}

In your header.css file, add the following styles:

.head-text {
   position: relative;
}
.text-on-image {
  position: absolute;
  right: 50%;
  left: 50%;
  bottom: 15%;
}

This will position the text at the bottom center of the image.

The text-on-image div's position is determined by the parent div with position: relative.

You can adjust the values of right, left, and bottom to place the text where desired.

For more examples and ideas, check out this link

Answer №2

Here's a suggestion for achieving the desired effect:

<section>
  <img src = {require ('../ images / Header.png')} alt = "Freedom Blog" />
  <h3> Welcome to my Freedom Blog </h3>
  <p> Embrace FREEDOM! </p>
</section>
header {
  position: relative;
  text-align: center;
  padding-top: 25px;
}
header img {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

Answer №3

<div className = "head-text">
        <div className = "head-image">
          <img src = {require ('../ images / Header.png')} alt = "Freedom Blog" />
        </div>
        <div className="center__text">
          <h3> Welcome to my Blog </h3>
          <p> FREEEEDOM </p>
        </div>
</div>

Follow these steps:

.head-text{
position: relative;
color: white;

The text color specified above will be the color of your text.

.center__text{
position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Your text will now be centered on your image.

Answer №4

To handle text on an image, you can use the following code in tailwindcss:

<Div className="relative flex flex-row-reverse justify-between items-center rounded-3xl">
    <Img
      src="./sky.webp"
      className="absolute w-full h-full top-0 left-0 object-cover rounded-3xl bg-transparent"
    />
    <Span
      className=" rounded-[21.9px]  flex flx-row justify-center items-center w-full h-full text-[150px]  dark:bg-darkBackground"
    >
      Let's Talk
    </Span>
  </Div>

You have the option to delete mixBlendMode from the code.

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

Show the parsed HTML content within a TextView widget

I am encountering an issue with displaying HTML content in a TextView. The content is dynamically parsed using JSON parsing. Upon trying the provided link in a browser, below is an excerpt from the JSON response received: <p><font color='#FF ...

Building a dynamic hierarchical list in Angular 8 with recursive expansion and collapse functionality

I am attempting to construct a hierarchical expand/collapse list that illustrates a parent-child relationship. Initially, the parent nodes will be displayed. If they have children, a carat icon is shown; otherwise, a bullet icon appears. When the carat ico ...

Trouble with Loading jQuery Files on Beaglebone Server

Working on a wireless robotics project that involves using node.js and jquery to create a webpage "controller". Currently, the code is set up to work with an internet connection because it downloads scripts from internet addresses. The goal is to make it ...

React - Error: Unable to access the 'props' property because it is undefined

I am working on implementing a click event to delete an item from my list, but I keep encountering the error message "TypeError: Cannot read property 'props' of undefined" whenever I click on it. Although I am striving to follow ES6 standards as ...

The React functional component captures a snapshot of its state when initializing a websocket event handler

When using a react functional component, it captures a snapshot of the state at the time of subscription. For example, refer to the code below. If I click the setSocketHandler button and then press the setWelcomeString button. If I receive a message over ...

What is the best way to end a session?

I'm having trouble destroying a session after the user logs out. The current code I've used doesn't seem to be working as expected. Despite being able to print the console.log() from the logout route, the session remains active. Here is th ...

If I do not specify whether a variable is declared using var or let, what will be its scope?

As someone who is new to JavaScript, please forgive me if my question is not entirely valid. What will be the scope and type (var/let) of a variable if I do not specifically define it as var or let? For example: function f1(){ a="Sample" console.log(" ...

Jquery spinner overlay for enhanced loading experience

Currently, I am incorporating jQuery/Ajax in my project and wanted to include a spinner when an ajax request is made. The specific scenario involves two tabs on the UI: Home and Activities. When the user clicks on the Activities tab, an ajax request is sen ...

Action outcome yielding identical content

Is there a way in MVC C# to return an ActionResult without making any changes to the view? I have attempted: Returning null and new EmptyResult(), but these result in an empty page Returning an empty JavaScript (again, resulting in an empty page) Retur ...

Transform vertical and horizontal scrolling actions into solely horizontal scrolling using HTML and JS

I'm currently working on a unique React.js website that features a horizontal-scrolling portfolio. The website functions as a visual gallery, allowing users to easily scroll through images using their trackpad. Within the website, I have set up a lar ...

Updating Content in HTML Code Generated by JavaScript

My goal is to change the innerHTML of a div when it's clicked. I have an array of dynamically generated divs, and I want to target the specific table that the user clicks on. I attempted to set the IDs of the tables dynamically in my JavaScript code: ...

Retrieving information enclosed within a tag

I have been researching this topic and trying to implement various solutions, but I am not achieving the desired output. Here is the HTML code snippet: <div class="span-8"> <dl> <dt> <a title="A Coruña" href="http://www. ...

Sending requests from a React application to a Node.js backend hosted on an Nginx server with SSL enabled

After creating static files for a reactjs app using the create react app tool, I launched an nginx server on a docker container to serve the front end built with reactjs. This nginx server communicates with a node js in another container. Everything was r ...

The Safari browser showcases the dropdown area in a unique way

Is there a way to make the dropdown area size consistent across different browsers like Chrome, Firefox, and Internet Explorer? Here is the code snippet: <div id="category-dropdown" style="float:left; display:inline-block; padding:8px 0px 0px 5px; dis ...

Populate items on the webpage with data from a JSON document

Looking for a more efficient way to handle text in my multilanguage web application. I currently store all text in a JSON file and load it for each element on every page using JQuery, like this: $("h1.text1").append(data[language]['startpage'][0 ...

HTML textarea fails to recognize inline styles

My journey with JHipster began recently when I embarked on my first project. Two entities were created, one of which resembles a blog. This particular blog entity has a content attribute that interacts with a textarea. In my blogs.html file, I allowed the ...

Creating a column heading that appears at the top of each column break with the help of CSS column-count

Is there a way to output a list into x number of columns within a content div without specifying the exact amount of columns in CSS? I also want to include a heading at the top of each column: Firstname Lastname State Firstname Lastname State ...

It appears that React is not successfully transferring props to another component

Recently, I decided to follow a tutorial on creating a React application. However, I encountered a peculiar issue that has left me scratching my head. The problem arises when I attempt to pass data from one component to another. Despite successfully passi ...

ReactJS: Unable to navigate to a new page when moving from a page with automatic refresh

Every 5 seconds, I automatically refresh a page (Page1) using setTimeout and a callback function. However, every time I navigate to a new page (Page2), it quickly redirects back to Page1 after a few moments. I have tried using window beforeunload event l ...

How to Style an Element Based on Fragment Identifier in Href Attribute Using CSS

I've implemented the tabview feature from the YUI3 library. This is how the markup code appears: <div id="demo" class="yui3-tabview-content"> <ul class="yui3-tabview-list"> <li class="yui3-tab yui3-widget yui3-tab-selected"> ...