MaterialUI Box接管背景图片

时间:2019-12-27 12:46:18

标签: css reactjs material-ui

我有一个包含表单的react组件,其格式如下:

~/my-function$ aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip

此组件,称为Form,然后在<Box display="flex" justifyContent="center" alignItems="center" style={{ minHeight: "100vh", backgroundColor: "gray", opacity: "0.8" }} > ... </Box> 中传递,如下所示:

App.js

但是,我得到的结果是这样的:

enter image description here

我添加了不透明度,以更好地显示我的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; 组件在整个窗口中都“拉伸”,而我希望它只包装其内容,因此,如果应用了一些不透明度,则它只会出现我站在Box旁边,背景图片将正常显示。

我该如何实现?

2 个答案:

答案 0 :(得分:1)

material-ui Box的默认组件是div。参见material-ui Box

div的默认行为是在可用空间中水平拉伸。这就是为什么Box会水平拉伸的原因。 Where is the default size of a div element defined or calculated?

您要在Box上使用的minHeight:“ 100vh”样式要求它在可用的垂直空间上伸展。这就是为什么Box垂直拉伸的原因。 参见Fun with Viewport Units

也许将Grid组件用作包装器会为您提供所需的东西

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

这会将您的代码更改为:

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;

答案 1 :(得分:0)

我建议您使用pseudo:after之类的:before元素

这里是一个例子。

.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>

  

做任何你想应用于::after的事情都不会影响上面的表格