Is there a way to adjust the image opacity of a background using Material UI?

Is there a way to adjust the opacity of a background image using Material UI? I attempted to achieve this by utilizing the makeStyles hook in Material UI. Here is an example of my code:

import React from 'react';
import {Box,Typography } from '@mui/material';
import { makeStyles } from '@material-ui/core/styles';


const CategoryCard = ({ image }) => {
    const useStyles = makeStyles({
        demowrap:{
            position:'relative'
        },
        '&::before':{
            content: '"',
            display: 'block',
            position: 'absolute',
            left: 0,
            top: 0,
            width: '100%',
            height: '100%',
            opacity: 0.6,
            backgroundImage: `url(${image})`,
            backgroundRepeat: 'no-repeat',
            backgroundPosition: '50% 0',
            backgroundSize: 'cover'
        },

        demoContent:{
            position:'relative'
        }
    })
  

    const classes = useStyles()
    return (
        <Box component="div" className={classes.demowrap}>
            <Box  component="div" className={classes.demoContent} > 
                <Typography component="p">Hello</Typography> 
            </Box>
        </Box>
    );
};

export default CategoryCard;

Unfortunately, I am encountering difficulties as the image is not displaying correctly on the UI. Any assistance would be greatly appreciated. Thank you.

Answer №1

Give this a shot. I believe it should do the trick.

const customStyles = makeStyles({
        boxWrap:{
            position:'relative',
            '&:before':{
                  content: '""',
                  display: 'block',
                  position: 'absolute',
                  left: 0,
                  top: 0,
                  width: '100%',
                  height: '100%',
                  opacity: 0.6,
                  backgroundImage: `url(${image})`,
                  backgroundRepeat: 'no-repeat',
                  backgroundPosition: '50% 0',
                  backgroundSize: 'cover'
            }
        },
        contentSection:{
            position:'relative'
        }
    })

Answer №2

To achieve the desired effect, place the background image in a pseudo-element of the parent container:

.container::before {    
  content: "";
  background-image: url('https://example.com/image.jpg');
  background-size: cover;
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  opacity: 0.75;

} Ensure the parent element has a relative position and set its height and width like this:

.container {
position: relative; 
height: 100vh;
width: 100%;
display: flex;
align-items: center;
justify-content: center;

}

If you want to add an overlay with reduced opacity and color on top of the background image, use the following CSS:

.container::after {
content: "";
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
background-color: rgba(0,0,0,0.25);

}

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

Guide to successfully integrate MathJax into your React application

I developed an application using HTML that successfully rendered MathJax equations through a script tag. However, after transitioning to React, the MathJax equations are no longer appearing. I have tried adding the MathJax script (shown below) in the comp ...

Can you demonstrate how to incorporate a new line within a for loop?

I have an array of letters and I need to display them on the screen using a for loop. My goal is to make every sixth letter appear on a new line. Here is the code snippet: https://i.stack.imgur.com/lHFqq.jpg <script> export default { data() { ...

What is the best way to conceal a bootstrap directive tooltip in Vue.js for mobile users?

Currently, I'm tackling a project with Vuejs and Laravel. There's a tooltip directive incorporated that relies on Bootstrap's functionality. Check it out below: window.Vue.directive("tooltip", function(el, binding) { // console ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

Declaring a sophisticated array as a property within another property in Typescript

As a newcomer to Angular and Typescript, I am facing a challenge while declaring a property with a complex array as one of its values. Here is what I have attempted: groupedItem: { customGroupId: string, cgName: string, category: [{ cu ...

Error message: It seems the spatial reference for this ESRI object is missing

Currently, I am utilizing Esri GIS to load the center location from an address. However, I am encountering an issue as I am using a geocoder from Google to obtain longitude and latitude, which is resulting in the following error message: TypeError: this.s ...

Troubleshooting: Configuring dynamic minimum time for <input type='time'> in AngularJS not functioning as expected

Can someone help me with setting the minimum time dynamically to the current time? For some reason, it's not working and I'm not getting any error messages. Where did I make a mistake? $scope.mintime = new Date(); <label class="item item-in ...

I'm encountering an issue with fetching table data using AJAX, as I consistently receive an undefined value in Console.log every time I try to fetch req_id from the table. Can anyone help me

I am struggling to fetch the req_id from the table as it always shows undefined in Console.log(). Despite having a successful database connection and data availability in the table, I have attempted both GET and POST methods without success. My main goal i ...

To style a text box next to text within a paragraph in CSS, simply create an empty box

I have some CSS classes defined as follows: .p_box { position: relative; } .p_box span { background-color: white; padding-right: 10px; } .p_box:after { content:""; position: absolute; bottom: 0; left: 0; right: 0; top: ...

What is the best method to close a polygon infowindow when hovering over a map marker?

I am currently working on integrating Google Maps which includes a set of polygons representing state boundaries and markers representing cities within each polygon. I want to display information when hovering over a polygon/state. My question is: how can ...

Exporting Next.js sitemap statically

Can anyone assist me in creating a Sitemap for my NextJs project? I have developed a headless CMS using GraphQL and Next, with everything being statically generated. However, I am facing challenges when it comes to generating a sitemap. I attempted to use ...

Cross-origin resource sharing (CORS) will still be ineffective, even when the Access-Control-Allow-Origin

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus quis est eu arcu tincidunt pulvinar. Aenean vel sapien vitae quam varius vulputate. Vestibulum et lacinia sem. Vivamus tristique mi ac metus tincidunt eget. // Donec fermentum al ...

Using Superagent in React: Executing a function within a callback

How can I call a function at the end of a request using Superagent to get the response? request.post('/TextUpload') .send({title:this.state.title1}) .end( function(res){ console.log(res); this.myFunction(); }) I keep receiving the error m ...

Visibility of the br tag is not detected

I need to keep one specific div visible on the page while hiding all other content. However, I am facing an issue where the <br> tag inside that div is not showing up. <div id='min320'>min 320px<br>screen width required</div ...

Experiencing issues with Errors when Targeting ES5 in Angular2 TypeScript?

In my development environment, the npm version is 3.10.10, and I want to create a new Angular2 project from scratch. When I try running npm install angular2 --save I encounter this error message: Error Image After referring to this answer which recomm ...

What is the best way to ensure that text fields remain hidden upon page load until the appropriate drop down option is chosen?

Is it possible to initially hide text fields and only reveal them when a specific drop down option is selected? The current JavaScript code somewhat achieves this, but I would like the input fields to remain hidden by default. <script language=" ...

Achieve a div to fill the remaining width while using list-style-position: inside

I have been attempting to make another div occupy the remaining space in the numerical list item using list-style-position: inside, but it does not seem to be working for me. While I could opt for list-style-position: outside and add some spacing to avoid ...

Function in AngularJS to increment counts based on matching names

Check out my angular application on this Plunker link The text area in my app contains data in the format of (key, count). My goal is to sum up these values using the calc() function. When the user clicks the button, I want the total summation to be disp ...

How can I stack two appbar components from Material Ui on top of each other without the vertical line separating them?

I am facing a challenge while trying to incorporate two AppBar components in Material-UI, stacked one on top of the other. The problem arises when a line appears at the end of the first AppBar, overlapping with the second one. Click here to view an image ...

Ways to incorporate input with redux

Seeking assistance with creating a todo-app using redux. Struggling to render input data and unable to create items when clicking the button. Any guidance on utilizing input with redux would be greatly appreciated. Visit the project here. Thank you! import ...