MaterialUI Box reigns supreme in the realm of background images

In my React component, I have a form that is structured like this:

<Box
      display="flex"
      justifyContent="center"
      alignItems="center"
      style={{ minHeight: "100vh", backgroundColor: "gray", opacity: "0.8" }}
    > ...
</Box>

This form component, named Form, is then included in App.js in the following way:

import React from "react";
import Form from "./components/Form";

const sectionStyle = {
  height: "100vh",
  backgroundImage:
    "url('www.blablabla.com/img.jpg') ",
  backgroundRepeat: "no-repeat",
  backgroundSize: "cover"
};

const App = () => {
  return (
    <div style={sectionStyle}>
      <Form />
    </div>
  );
};
export default App;


However, the output I get looks like this:

https://i.sstatic.net/1jENj.jpg

I used opacity to emphasize that my Box component is covering the entire window, whereas I want it to only wrap around its content. This way, if opacity is applied, it will only affect the inside of the Box, while the background image remains unaffected.

Is there a way for me to achieve this?

Answer №1

material-ui Box's default component is a div. For more information, visit material-ui Box

A div typically stretches horizontally by default to fill the available space. This explains why your Box is stretching horizontally. To learn more about how the default size of a div element is determined or calculated, check out this resource: Where is the default size of a div element defined or calculated?

The minHeight: "100vh" style applied to the Box instructs it to stretch vertically across the available space. Consequently, your Box is stretching vertically. For a fun exploration of viewport units, see: Fun with Viewport Units

If you're looking for a different layout, consider using the Grid component as a wrapper. Here's an example:

   <Grid container className={props.classes.sectionStyle}
                          direction="column"
                          justify="space-evenly"
                          alignItems="center"
   >
       <Grid item>
           <Form />
       </Grid>
   </Grid>

To implement this change in your code, you can do the following:

import React from "react";
import {Grid} from '@material-ui/core';
import Form from "./components/Form";

const sectionStyle = {
  height: "100vh",
  backgroundImage: "url('www.blablabla.com/img.jpg') ",
  backgroundRepeat: "no-repeat",
  backgroundSize: "cover"
};

const App = () => {
  return (
    <Grid style={sectionStyle}
        container
        direction="column"
        justify="space-evenly"
        alignItems="center"
    >
      <Grid item>
        <Form />
      </Grid>
    </Grid>
  );
};
export default App;

Answer №2

If you are looking for a solution, my suggestion would be to utilize pseudo-elements like :after and :before

Take a look at this example.

.background-filter::after {
    content: "";
    display: block;
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: .8;
    background: red;
}

.background-filter {
  position: relative;
}

.background {
  background-image: url('https://upload.wikimedia.org/wikipedia/en/6/62/Kermit_the_Frog.jpg');
  width: 200px;
  height: 200px;
}
.background span{
position: absolute;
    z-index: 1;
    }
<div class="background background-filter"><span>Hello World I am text with background blur</span></div>

The changes made to ::after will not impact the form above

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

Is there a way to simulate location data from the router in enzyme testing?

Looking for help with this code snippet... <BrowserRouter> <Switch> <Route path='/' exact component={Main} /> <Route path='/transcript' component={Transcript} /> < ...

Finding strikeout text within <s> or <del> tags can be identified by closely examining the HTML codes

The issue arises with the text that reads as follows: 316.6.1 Structures. Structures shall not be constructed This is represented in HTML as: <b> <s> <span style='font-size:10.0pt'>316.6.1 Structures</span> ...

Tips on how to optimize form input mapping without losing focus on updates

I am facing an issue with a form that dynamically renders as a list of inputs. The code snippet looks like this: arrState.map((obj,index)=>{ return( <input type="text" value={obj} onChange{(e) => stateHandler(e,index)}<inpu ...

Obtaining cookies on the client side with Next.js

I am currently struggling to verify the existence of a particular cookie and remove certain data from redux if it is not present. Despite utilizing a package named 'cookies-next', I am unable to access the cookies. My approach involves using a c ...

Which element is able to utilize the inline-block style?

Currently, I am delving into the intricacies of the inline-block attribute and have a basic understanding that it allows elements to sit on the same row rather than stack on top of each other as they would in a normal layout. However, my grasp on how exact ...

Is it possible that the div's height is not being set to 0 pixels

<div style="height:0px;max-height:0px"> </div> It appears that setting the height of a div to 0 pixels is not having the desired effect. The div is still expanding to display its contents, so how can we stop this from occurring? ...

Tips for maintaining the original value of a state variable on a child page in ReactJS. Keeping the initial value passed as props from the parent page

Whenever the 'isChildOpen' flag in the parent is true, my child page opens. The goal now is to ensure that the state variable filtered2 in the child component remains constant. While both filtered and filtered2 should initially receive the same v ...

The div element is not extending all the way to the left side of the browser window

I'm having trouble positioning a menu at the top of my webpage following a tutorial. The menu icon doesn't seem to reach all the way to the left side of the page. Despite multiple attempts to adjust the margin and padding settings, I can't ...

What happens when the loading state does not update while using an async function in an onClick event?

I'm currently working on implementing the MUI Loading Button and encountering an issue with changing the loading state of the button upon click. Despite setting the state of downloadLoading to true in the onClick event, it always returns false. The p ...

Using MUI-X autocomplete with TextField disables the ability to edit cells

When I double-click on a cell, everything works fine. However, after the second click to start editing the textfield, the cell stops editing. I can still choose an option though, so I believe the issue lies somewhere in the textField component, possibly i ...

Unlock the innerHTML of a DIV by clicking a button with ng-click in Angular JS

I am curious about something. There is a <div> and a <button> in my code. I am looking to access the inner markup of the <div> within the ng-click function without relying on jQuery. Can you give me some guidance? <div id = text-entry ...

I'm curious if there is a method to specifically update a single cell entry within MongoDB using nodes and express js

Is there a way to update a single record in a mongoDB database? I need to specifically update the value of CAD in the data provided below. [ { _id: new ObjectId("615564fbab33d4da1ab2d9bb"), AUD: 20, CAD: 92.8, CHF: 69.14, EU ...

Using CSS files that are not properly imported into React components

Currently, I am utilizing multiple CSS files for a specific purpose. The issue I am facing is that when I apply styles to one component in a CSS file, it inadvertently affects other components as well, not just the intended one. I believe the root of this ...

Elements Fail to Display After Updating State with UseState

This question presents a challenge due to its complexity, but I will try to clarify the situation before delving into the code implementation. My aim is to create a screen for managers displaying all their drivers with minimal information and an edit butto ...

Positioning a Material UI Menu item underneath its parent element using CSS styling

I have created a Material UI dialog that features some text and an Icon with a dropdown menu option. You can check out the demo here: https://codesandbox.io/s/prod-rain-1rwhf?file=/src/App.js My goal is to properly position the Menu component so that it a ...

What is the proper way to specify the background image path in CSS?

My CSS file is located at: Project/Web/Support/Styles/file.css The image I want to use is found here: Project/Web/images/image.png I am attempting to include this image in my CSS file. I have tried the following methods: 1) background-image: url(/images ...

Testing form submission in React with React Testing Library and checking if prop is called

Feel free to check out the issue in action using this codesandbox link: https://codesandbox.io/s/l5835jo1rm To illustrate, I've created a component that fetches a random image every time a button is clicked within the form: import { Button } from " ...

Initiating the export of MUI DataGrid to CSV by clicking a button

I have been utilizing the @mui/x-data-grid which allows me to export table data to CSV using <GridToolbarExport />, and it works perfectly. However, I am wondering if there is a method to trigger this export functionality from another button, like th ...

Next.js encountered a Runtime Error: Trying to access properties of undefined (specifically 'status') and failing

For those interested in viewing the code, it can be found here During the creation of a portfolio website using Next.js, I encountered an error. I am utilizing the latest version of Next.js (next 13.4.16) and incorporating the app router into my project. ...

Switch Material UI IconButton Icon upon clicking

I'm trying to manage the state of an IconButton within a DataGrid component. How can I ensure that when the onClick event is triggered, the icon inside the IconButton changes accordingly? <IconButton size="small" onClick={e => { ch ...