首页 > 解决方案 > css 背景颜色属性

问题描述

css 背景属性中的这种语法效果很好:

 .my-element {
          background:
            linear-gradient( rgba(131,131,131,0.8), rgba(98,98,98,0.8) ),
            url('img/background.jpg')
}

我不需要渐变。我希望叠加层来自一种具有一定不透明度的颜色。我知道我可以让起始颜色与渐变的结束颜色相同,但是是否可以用包含不透明度的 rgba 颜色替换“线性渐变”?它似乎不起作用。

编辑:我的问题可能不清楚。我想要的是:

.my-element {
              background:
                color(rgba(131,131,131,0.8),
                url('img/background.jpg')
    }

以上不起作用。我也不能对颜色使用十六进制表示法,因为它不包括不透明度。

标签: cssbackground

解决方案


你有两种可能。

要么考虑使用 CSS 变量来优化代码并避免重复颜色两次:

.box {
  --c:rgba(131,131,131,0.8);
  
  height:300px;
  width:300px;
  background:
    linear-gradient(var(--c),var(--c)),
    url(https://i.picsum.photos/id/1002/800/800.jpg) center/cover;
}
<div class="box"></div>

或者使用混合,但您可能没有完全相同的结果,您需要根据使用的颜色调整混合值:

.box {
  height:300px;
  width:300px;
  background:
    url(https://i.picsum.photos/id/1002/800/800.jpg) center/cover,
    rgba(131,131,131,0.8);
  background-blend-mode: exclusion;
}
<div class="box"></div>


推荐阅读