How to add black overlay on image in react using css?

Hi Friends πŸ‘‹,

Welcome To aHoisting!

To add black overlay on image in react using css, you can set background-color: rgba(0, 0, 0, 0.5); in .overlay. It will add black overlay on image in react using css.

Today, I am going to show you, how to add black overlay on image in react using css.

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

import React from "react";
import "./App.css";
import logo from "./beautiful-nature.jpeg"

Step 3: Create a Component.

You can use className="overlay" to add black overlay on image in react using css.

<div className="image-container">
  <img src={logo} alt="Example" className="image" />
  <div className="overlay"></div>
</div>

Add black overlay on image example.

The below code is an example of a React. You have to import "./App.css" and set background-color: rgba(0, 0, 0, 0.5); in .overlay to add black overlay on image in react using css.

App.js

import React from "react";
import "./App.css";
import logo from "./beautiful-nature.jpeg"

const App = () => {
  return (
    <div className="image-container">
      <img src={logo} alt="Example" className="image" />
      <div className="overlay"></div>
    </div>
  );
};

export default App;

App.css


.image-container {
  position: relative;
  display: inline-block;
}

.image {
  width: 50%;
  height: 50%;
  display: block;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 50%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* Black with 50% opacity */
  z-index: 1; /* Layer it above the image */
  pointer-events: none; /* Prevent it from blocking interactions */
}

In the above code example, I have used the background-color: rgba(0, 0, 0, 0.5); to add black overlay on image in react using css.

Check the output of the above code.

React, black, overlay, on, image

All the best πŸ‘