What is the best way to apply a color overlay to an image using CSS?

In my current project, I am utilizing React along with HTML, CSS, and Material UI. One of the tasks I am working on is toggling a color overlay on an image when it is clicked.

Here is the snippet of JavaScript code I have implemented:

const About = ({imgState, setImgState}) => {

const imgTracker = () => {
    if(imgState === true){
      setImgState(false);
    }
    else if(imgState===false){
      setImgState(true);
    }
  }

...

<Box
                  className={imgState ? 'AboutImg active' : 'AboutImg notactive'}
                  component="img"
                  alt="face"
                  src={img2} 
                  onClick={imgTracker}      
                />

Additionally, here is the corresponding CSS markup:

.MidSectionTop{
    .MidSectionTopText{

    }

    .MidSectionImage{
        .AboutImg{
            height: calc(100vh * 4/12);
            width: calc(100vw * 2/12);

            &.active{
                background: rgba(0, 197, 165, 0.5);
                
            }
            &.notactive{
                background: none;
            }
        }
    }
}

My current issue lies in the fact that the image overlays on top of the background color applied. I attempted to use z-index with the '&.active' class, but it did not yield the desired result. Any guidance or suggestions would be greatly appreciated! Please let me know if there is any additional information I can provide to help troubleshoot this problem further.

Answer №1

To achieve this effect, you can utilize pseudo-elements like ::before and ::after.

.HeroBanner{
    position: relative;
    &::after{
        position:absolute;
        left:0;
        top:0;
        right:0;
        bottom:0;
        display:block;
        content: '';
    }
    &.active::after{
        background: rgba(255, 99, 71, 0.5);
    }
    &.inactive::after{
        background: none;
    }
}

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

Error message: Invalid input for directive, only numeric values are accepted

I need help with a directive that restricts non-numeric symbols in an input field. Below is the code for the directive: import { NgControl } from "@angular/forms"; import { HostListener, Directive } from "@angular/core"; @Direct ...

Create a div element that can be expanded on smaller devices

Is it possible to expand a div while hovering on a small or x-small device? I want to achieve something like this: https://i.sstatic.net/doJKa.png Currently, I can only hide the yellow div when the page is displayed on a small device. I am looking for a ...

Even after modifications to the formGroup control, the value remains null when using ng-select, unless the searchTerm is provided programmatically

I need to programmatically set the value of the searchTerm using a virtual keypad, and the dropdown should display options based on the searchTerm. The form control is set to updateOn:'blur'. However, I am facing an issue where the form control ...

Show the profile picture of a model in a Django template

I am trying to display the user's image by inserting it into the src attribute of the img tag, but I am facing difficulties with it. Here is my code: models.py class allusers(models.Model): user = models.OneToOneField(User, on_delete=models.CASC ...

Is it possible to include multiple data arguments in the useMutation hook in react-query?

The structure of the useMutation Hook argument is defined as follows in the guide: const { data, error, isError, isIdle, isLoading, isPaused, isSuccess, mutate, mutateAsync, reset, status, } = useMutation(mutationFn, { cacheTime, ...

What is the most effective way to store HTML templates on a webpage?

As I work on developing a complex JavaScript interface for my website, I have decided to utilize the jQuery templates plugin to create elements based on queries to a JSON API. However, I am faced with an issue: I anticipate needing numerous templates for ...

Struggling to grasp the concept of Vue3 style binding

While browsing the Vue website, I came across a particular example that left me puzzled. Inside the <script> section, there is this code: const color = ref('green') function toggleColor() { color.value = color.value === 'green' ...

Ways to resolve issues with resizing div elements while waiting for JavaScript to load

Apologies for the lack of a clear title to describe my issue. My problem involves this snippet of code, where I am creating a label to show time to users. <div class="content"> <div class="container"> <div class="card"> < ...

Access to property 'nodeType' on AJAX request in Firefox has been denied due to permission error

On my webpage, I have integrated the Google Sign-in button along with gapi for interaction. After a successful authentication using the Google API, an AJAX call is made to the server using JQuery: var token = gapi.auth.getToken(); var data = { "to ...

Playing videos from the client machine using HTML5

I seem to be having trouble playing videos from my CLIENT MACHINE using HTML5. Below is the syntax I am currently using. <div> <video width="320" height="240" controls autoplay="autoplay"> <source src="file://D:/Videos/bigbuckbunny.mp4" typ ...

"Utilizing social links in web design for a seamless user experience

I'm currently exploring ways to repair the design of social media links. The GitHub and Spotify icons are displaying at different sizes, and it seems like the Blogger icon is not aligning correctly: https://i.sstatic.net/7j4Hr.jpg Referring to How ...

Using jQuery to trigger events depending on the Hash portion of the URL

Hello everyone, I am relatively new to javaScript/jQuery and still learning the basics. I recently discovered that it is possible to change the hash of a URL onClick. However, I am curious if there is a way to addClass/removeClass from an element, hide/sh ...

Tips for choosing a drop-down menu option without an identifier using Selenium in Python

I am trying to choose an element/item from a drop-down menu in Python and Selenium without using an id element. Here is the HTML code snippet: <mbo-transaction-mode-select mode="filters.mode" class="ng-isolate-scope"> <select class="form-con ...

The type 'function that takes in a CustomEvent and returns void' cannot be assigned to a parameter of type 'EventListenerOrEventListenerObject'

When I upgraded from TypeScript version 2.5.3 to 2.6.1, my custom event setup started giving me an error. window.addEventListener('OnRewards', (e: CustomEvent) => { // my code here }) [ts] Argument of type '(e: CustomEvent) => ...

Tips for retrieving the output from an Azure Function

Just getting started with Azure Functions and I have this code snippet: module.exports = function (context, req) { context.log('JavaScript HTTP trigger function processed a request.'); context.log(context.req.body.videoId) ...

Labeling with the index number of arrays

var arr = []; $('.inp').click(function(){ function arrcall() { $.each(arr, function(key, value) { alert('Array Key is: ' + key + ' \n Array Key value is: ' + value); }); } ...

Is there a way to extract the visible text from an HTML TextNode without including the HTML tags?

My current challenge involves converting a DOM node and all of its children into plain text markup of a custom design. Utilizing node.childNodes allows me to retrieve a list of all content, which can then be recursively transformed into my desired string f ...

What is the correct way to reference this data element in Ajax?

I am attempting to retrieve the elevation data for 732 meters from the JSON API response below: {"results":1,"data":[{"wind":{"degrees":200,"speed_kts":6,"speed_mph":7,"speed_mps":3,&quo ...

An unexpected error occurred with React JS stating: "Parse Error: Line 27: Unexpected token . at http://localhost/PHP-React-Demo/ajax_call.html return {cell.data.row}"

I need help in showing data from a database in a React JS application. Encountered error in React JS: Error: Parse Error: Line 27: Unexpected token . at http://localhost/PHP-React-Demo/ajax_call.html return {cell.data.row} This is my code: Index.p ...

Error message: JSON.parse encountered an unexpected "<" token at the start of the JSON input

Currently, I am looping through an object and sending multiple requests to an API using the items in that object. These requests fetch data which is then stored in a database after parsing it with JSON.parse(). The parsed data is sent to a callback functio ...