Best method for overlaying a div on top of an image using HTML and CSS

As a beginner in programming, I've taken on a project to enhance my skills.

I'm looking to add a div with text overlaying an image, similar to the example shown below:

https://i.sstatic.net/AnfM2.png

The goal is to have half of the div display an image and the other half show text. Can you guide me on how to achieve this?

Below is the code I've implemented in codesandbox

import React from "react";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <h1>Restaurant</h1>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          justifyContent: "baseline",
          alignItems: "baseline",
          height: "200px",
          width: "100%",
          maxWidth: "300px"
        }}
      >
        <div>
          <img
            style={{
              width: "100%",
              height: "100%"
            }}
            src="https://b.zmtcdn.com/data/collections/271e593eb19475efc39021c6e92603db_1454591396.jpg"
            alt=""
            className="img"
          />
        </div>
        <div className="divText">
          <span
            style={{
              color: "#fff",
              backgroundColor: "#000"
            }}
          >
            Lorem Ipsum! Lorem Ipsum! Lorem Ipsum!
          </span>
        </div>
      </div>
    </div>
  );
}

Thank you for your assistance!

Answer №1

Here are two ways to set a background image:

Method 1: Utilize the background properties in CSS

.backgroundImage {
  background-image:url("https://example.com/image.jpg");
}

Method 2: Use positioning for a customized layout

export default function Home() {
  return (
    <div className="Home">
      <h1>Welcome</h1>
      <div
        style={{
          position: "relative",
          height: "250px",
          width: "400px"
        }}
      >
        <img
          style={{
            width: "100%",
            height: "100%"
          }}
          src="https://example.com/image.jpg"
          alt=""
          className="image"
        />
        <div className="backgroundText"
          style={{
            position: "absolute",
            bottom: 0,
            height: "60%",
            width: "100%",
            color: "#fff",
            backgroundColor: "#000",
            opacity: 0.8
          }}>
            Customize your text here!
        </div>
      </div>
    </div>
  );
}

Answer №2

Perhaps a solution like this could work:

""
.container {
  width: 400px;
  height: 200px;
  position: relative;
}
picture {
  position: absolute;
  z-index: -1;
}

picture img {
  object-fit: cover;
  top: 0;
}

.text-overlay {
  top: 50%;
  height: 50%;
  position: relative;
  background-color: white;
  display: flex;
  z-index: 2;
  padding: 10px;
  opacity: 0.8;
  
  font-family: sans-serif;
}
<div class="container">
 <picture>
  <img src="https://images.unsplash.com/photo-1601758064224-c3c5ec910095?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2047&q=80"
  width="400px"
  height="200px"
  style="">
 </picture>
 
 <div class="text-overlay">
  <p>Hello</p>
 </div>
</div>

Answer №3

Here is my unique solution:

custom-style.css:

.customDivText {
  position: absolute;
  height: 50%;
  background-color: white;
  bottom: 0;
}

MainApp.js:

import React from "react";
import "./custom-styles.css";

export default function MainApp() {
  return (
    <div className="MainApp">
      <h1>Restaurant</h1>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          justifyContent: "baseline",
          alignItems: "baseline",
          height: "200px",
          width: "100%",
          maxWidth: "300px",
          position: "relative"
        }}
      >
        <div
        style={{
          height: "inherit"
        }}>
          <img
            style={{
              width: "100%",
              height: "100%"
            }}
            src="https://example.com/image.jpg"
            alt=""
            className="main-img"
          />
        </div>
        <div className="customDivText">
          <span
            style={{
              color: "#fff",
              backgroundColor: "#000"
            }}
          >
            Unique Content! Unique Content! Unique Content!
          </span>
        </div>
      </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

Tips for handling trycatch block and generics with axios

Seeking advice on handling Axios and typescript errors. Issue arises with returning errors due to a Type error involving Promise not being of type number | undefined, specifically originating from the catch block. How can I elegantly manage this scenario? ...

divs aligned vertically on opposite edges of the webpage

Our web app is being embedded in a third party page as an iframe, but we need to add a bottom "toolbar" with 2 links. One link should be plain text and the other should display our company logo preceded by some text. We want the two links to be positioned ...

Having difficulty accessing `props` in a React JS and Next JS application

Currently, I am developing a React application that utilizes Server Side Rendering. In this project, I am using React Js and Next Js as my primary framework. My goal is to retrieve initial props using the getServerSideProps method by consulting the documen ...

Files with extensions containing wildcards will trigger a 404 error when accessed from the public folder in NextJS

I have successfully set up my public folder to serve static files, however I am encountering an issue with files that have a leading dot in their filename (.**). Specifically, I need to host the "well-known" text file for apple-pay domain verification, wh ...

Positioning an item beneath two floating objects

Trying to create a visually interesting element on my website with 2 circles overlapping their parent element and 1 overlapping below. How can I make the third one centered below the first two? I've experimented with float left and right, but not sur ...

Maintaining binding while appending inner elements within a container using jQuery

I'm struggling to transfer the contents of one container to another without losing any bindings, and it's proving quite tricky! <div class="container"> <div class="field"> <label>Username</label> < ...

Switching the navigation drop down from hover to click: A step-by-step guide

I'm currently designing a responsive navigation bar with a dropdown feature that expands on hover. However, I've encountered an issue as this hover effect is not ideal for mobile devices. Therefore, I am looking to modify my navigation bar so tha ...

Is the on-error event not functioning properly in the <img> tag?

I am currently utilizing VueJS to develop the front-end of a project and encountered an issue with the image tag when loading images. Template <div class="items" transition="fade" v-for="item in list"> <img :src="item.logoPath" @error="replac ...

Reverse the color of H1 text within a vertical div

Is it feasible to reverse the coloring of a segment within an h1 element using a div, horizontally? Refer to the illustration shown in the image below. https://i.sstatic.net/QAKwD.jpg ...

Retrieving Data from Web using Python Selenium

I've been trying to extract information from a website (snippet provided below) The process involves entering data, moving to another page for more inputs, and eventually displaying a table. However, I'm encountering an issue at this stage: dri ...

Display the value of the dynamically added selected element only

Is there a way to display the selected element value on click without showing all element values? In the code below, when I add usernames and click on any label, it should only show the corresponding delete icon. However, currently, it shows delete icons f ...

The NG-CHANGE event will not be triggered when using an alertify popup window instance

Trying to create a settings modal window using alertify.js to change the background image of a page. However, when the modal is created, the ng-change functionality of the dropdown select is lost. It only works if the dropdown is on the main page. Select ...

Selecting a child element based on its position within an element with a

Is there a way to use CSS to select the nth child from an element with a specific class? For instance, in the scenario below, how would I target the li element with the id="this"? Essentially, I am looking to pinpoint the 2nd element within the element t ...

Executing memory function with JQuery replaceWith() and event handlers

Imagine you have the following HTML code: <button id="click-me" type="button">Click Me!</button> Now, picture this jQuery snippet being executed: var button = $('#click-me'); button.on('click', function() { console.l ...

Interactive Vue tree view featuring draggable nodes

I am currently working on creating a tree component in Vue.js, and I am facing challenges with implementing drag and drop functionality in the Tree component. I am unsure where to begin, as I have looked through similar code on GitHub but I am struggling t ...

Creating a bespoke Bootstrap 4 Modal experience without the backdrop

I'm attempting to show a Bootstrap 4 modal without a backdrop. I've tried the following code with no success: .modal.right. modal-backdrop.show { background-color: transparent !important; } When I try this modification, it works (but affect ...

The title attribute in Vue3 is updated through props, but computed properties remain unaffected

I incorporated an external library into my project using Vue3. The component I am utilizing is sourced from a third-party library [Edit: Upon realizing that the GitHub repository for this library is no longer being maintained, I have updated the code to re ...

Tips for dealing with React Native: Extracting items from AsyncStorage for use beyond async functions

I am encountering an issue where I am attempting to utilize an item from AsyncStorage, which is stored as a variable created within an async function. However, upon retrieval, it returns undefined. import React from 'react'; import {View,Text,To ...

Striving to design an event planner with the datepicker feature in javascript

Currently, I am integrating a javascript datepicker into my project to facilitate displaying a calendar and selecting a date for adding/viewing/editing events on that specific date. On my view, the datepicker calender is displayed within a div element. & ...

HookWebpackError: There seems to be an issue with reading the properties of undefined, specifically regarding 'e'. An inner error has occurred, resulting in a TypeError when trying to read properties of undefined for 'e'

I have been using npx-create-react-app for years, but now I am unable to build with npm run build. Even after updating my node and npm and clearing the cache with npm cache clean --force, the projects are still not working. Neither the old ones nor the ne ...