指定背景不透明度而不指定颜色



如何在不更改现有背景颜色的情况下指定background-color不透明度

例如,考虑:

div {
width: 100px;
height: 100px;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
.light {
background-color: rgba(?, ?, ?, 0.9) /* <--- what do I use here? */
}
<div class="blue"></div>
<div class="green"></div>
<div class="blue light"></div>
<div class="green light"></div>

我可以提供什么值来div.light更改不透明度而不覆盖/更改绿色/蓝色? 类似background-alphabackground-opacity的东西(不存在(

编辑:我根本不想改变div内容的不透明度;只是背景。

编辑:我知道有一些解决方案涉及添加DOM,但这违背了设计最佳实践(不要使用DOM进行样式设置(,我的目标是一个仅限CSS的解决方案。

您可以改用伪元素作为背景并使用opacity

div.blue::before {
background-color: blue;
}
div.green::before {
background-color: green;
}
div.light::before {
background-color: rgba(?, ?, ?, 0.9)
}
div::before {
content: '';
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
z-index: -1;
}
div {
position: relative;
}
.light::before {
opacity: .5;
}
<div class="blue">blue</div>
<div class="green">green</div>
<div class="blue light">blue light</div>
<div class="green light">green light</div>

我认为它不存在,但是您可以使用div的完整大小进行div.background,并使用文本,图像等进行div.content并添加opacity to div.background

最新更新