是否可以在CSS3中混合透明和纯色?

Goo*_*bot 6 css css3

是否可以在CSS3中从实体和透明颜色动态制作透明背景?例如:

<div class="red trans1">
CONTENT
</div>
Run Code Online (Sandbox Code Playgroud)

用CSS

.red {
background: #FF0000;
}
.trans1
background: rgba(255,255,255,0.5);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,纯色将完全覆盖透明度.当然,我的意思是使用不同的属性(background,background-color,等).

我有10种纯色,并希望为每种颜色创建10级透明度.如果为每种颜色单独制作透明色,则需要100个CSS类; 例如:

.red1 {
.background: rgba(255,0,0,0.1);
}
.red2 {
.background: rgba(255,0,0,0.2);
}
.red3 {
.background: rgba(255,0,0,0.3);
}
....
.blue1 {
.background: rgba(0,0,255,0.1);
}
.blue2 {
.background: rgba(0,0,255,0.2);
}
.blue3 {
.background: rgba(0,0,255,0.3);
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种混合纯色和透明背景的动态方式.

Sco*_*ttS 6

纯CSS

是的,您可以通过创造性地使用伪元素来取消颜色和透明度.例如,这个小提琴演示了以下代码(注意我已根据:after伪元素排列了所有内容):

HTML

<div class="opBkg red op10">Red 10%</div>
<div class="opBkg red op50">Red 50%</div>
<div class="opBkg blue op80">Blue 80%</div>
Run Code Online (Sandbox Code Playgroud)

相关的CSS

.opBkg {
  position: relative;
}

.opBkg:after {
  content: '';
  position: absolute;
  z-index: -1;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}

.red:after {
  background-color: red;
}
.blue:after {
  background-color: blue;
}
.op10:after {
  opacity: .1;  
}
.op50:after {
  opacity: .5;  
}
.op80:after {
  opacity: .8;  
}
Run Code Online (Sandbox Code Playgroud)

您将拥有10个不透明度规则,无论您想要多种颜色,然后是opBkg要设置的总体类.

  • +1 @All 不在这种情况下;“opacity”的这种使用仅影响伪元素。这非常聪明。 (2认同)