(CSS&React)我如何只将backgroundImage设置为一个组件?

时间:2019-03-20 11:24:45

标签: css reactjs css3 background-image

我正在尝试在React项目中的仅1个单个组件上设置backgroundImage。 如果我将其附加到 .body 元素,它将在所有组件上显示为backgroundImage。如果我将其设置为当前组件的 .wrapperContainer 元素,它将显示为

How it looks on .wrapperContainer

但是我想要的输出是这个(背景图像没有显示在所有其他组件上)

Desired look

CSS:

body {
background: url("../../services/images/hehe.jpg") no-repeat center center fixed; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover; 

animation: increase 60s linear 10ms infinite;
-webkit-transition: all 5.2s ease-in-out;
-moz-transition: all 5.2s ease-in-out;
-ms-transition: all 5.2s ease-in-out;
-o-transition: all 5.2s ease-in-out;
transition: all 5.2s ease-in-out;
z-index: -2;

background-color: #f6f8fa;

}

反应

  return (
  <div className="wrapperContainer"> /*This is the element i replace .body with*/
    <Card className="wrapperCard">
       xxxxxxx
       xxxxx
       xxx
</Card>
</div>
)

2 个答案:

答案 0 :(得分:0)

如果有帮助,请尝试这样

return (
  <div className="wrapperContainer" style={ { background: 'url("../../services/images/hehe.jpg") no-repeat center center fixed' } }> /*This is the element i replace .body with*/
    <Card className="wrapperCard">
       xxxxxxx
       xxxxx
       xxx
    </Card>
  </div>
)

答案 1 :(得分:0)

欢迎来到STACK Arasto。您可以将其设置为所需的组件名称。例如,您有背景仅显示在Card组件中。

现在假定Card的渲染功能如下:

<div className="bg-apply">

</div>

您可以在Card组件中为父div添加一个类,并按照问题的方式为该类添加样式。这样,样式/背景图片将仅应用于该特定的div /组件。

bg-apply {
background: url("../../services/images/hehe.jpg") no-repeat center center fixed; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover; 
animation: increase 60s linear 10ms infinite;
-webkit-transition: all 5.2s ease-in-out;
-moz-transition: all 5.2s ease-in-out;
-ms-transition: all 5.2s ease-in-out;
-o-transition: all 5.2s ease-in-out;
transition: all 5.2s ease-in-out;
z-index: -2;
background-color: #f6f8fa;
}