【问题标题】:Combine linear-gradient with dynamic background-image将线性渐变与动态背景图像相结合
【发布时间】:2019-06-20 13:30:54
【问题描述】:

我正在尝试在背景图像as demonstrated at w3school 上实现颜色叠加,但我想为动态设置的背景图像做它(我目前正在使用 VueJS)。

我想达到的目标:

<div class="hero-image">...</div>
.hero-image {
    background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('image.png');
    background-size: cover;
}

第一次尝试 - 将 background-image 提取到 html:

问题:这将覆盖颜色信息并仅使用 background-image 设置。我还尝试在 css 代码中使用 background 属性而不是 background-color

<div class="hero-image" :style="{ backgroundImage: `url('${image}')`}">...</div>
.hero-image {
    background-color: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5));
    background-size: cover;
}

第二次尝试——提取完整的背景属性:

问题:除了 background-size 属性现在被忽略之外,此方法有效。我尝试将 cover 添加到 html 中的 background 属性,但它也不起作用。

<div class="hero-image" :style="{ 
  background: `linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('${image}')`
}">...</div>
.hero-image {
    background-size: cover;
}

【问题讨论】:

  • 第二次尝试用background-image替换background,你可以使用background-size
  • 你也可以试试这样的:stackoverflow.com/a/54652984/8620333(将图片设为 CSS 变量)
  • 哇,谢谢@TemaniAfif,你的第一个答案就成功了!没想到这么简单..
  • 在您的内联样式中代替背景 - 使用 background-image 否则速记内联属性将覆盖您样式表中的背景大小

标签: javascript html css vue.js


【解决方案1】:

正如 Temani 所建议的,第二次尝试应该在 html 中使用 background-image 而不仅仅是 background。解决方案:

<div class="hero-image" :style="{ 
  backgroundImage: `linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('${image}')`
}">...</div>
.hero-image {
    background-size: cover;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多