【问题标题】:Background image with gradient overlay React带有渐变叠加的背景图像 React
【发布时间】:2021-01-17 19:10:09
【问题描述】:

我正在尝试为 div 设置背景图像并为其添加颜色叠加层。使用纯 CSS,它看起来像这样:

.backgroundImage {
 background-image:
 linear-gradient(to bottom, rgba(245, 246, 252, 0.52), rgba(117, 19, 93, 0.73)),
 url('../img/backgroundimage.jpg');
 width: auto;
 height: 40vh;
 background-size: cover;
}

但这种 CSS 方法对我不起作用,因为我正在构建的组件将被动态填充(不同的图片、文本内容等)。

我已尝试导入图像并执行与上述 css 相同的操作。不知何故,我可以设置背景图像,但无法让渐变叠加层在我的样式对象内工作。

所以我的下一个方法是将我的 div 包装在另一个 div 中并在那里设置渐变。这似乎也不起作用......

我希望比我聪明的人能回答这个问题...

干杯!

const wrapperPictureBox {
 background: "linear-gradient(to bottom, rgba(245, 246, 252, 0.52), rgba(117, 19, 93, 0.73))"
}

const pictureBox = {
 background: ` url(${backgroundimage})`,
 height: "40vh",
 backgroundSize: "cover",
};

 <div style={wrapperPictureBox}>
  <div style={pictureBox}>text</div>
 </div>

【问题讨论】:

    标签: css reactjs ionic-framework


    【解决方案1】:

    您可以采用 CSS 变量的方式。这个codepen 演示了。

    基本上,在React 文件中:

    <div style={{"--img": "url('https://images.unsplash.com/photo-1610907083431-d36d8947c8e2')"}}>text</div>
    

    而且,在 CSS 中:

    background-image: linear-gradient(to bottom, rgba(245, 246, 252, 0.52), rgba(117, 19, 93, 0.73)), var(--img);
    

    如果渐变也必须是动态的,那么类似的方法应该仍然有效。

    【讨论】:

    • 感谢您的帮助,现在可以使用了!只是出于好奇,我自己怎么会得出这个解决方案?我可能已经阅读了整个文档,但从来没有想出正确的解决方案......
    • 恐怕没有捷径可走。你被卡住了,找到了解决方案,几个月后,你可以在别人的代码中识别出这个问题。然后,您可以传授一点这种来之不易的经验。继续前进。
    猜你喜欢
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多