首页 > 解决方案 > 具有相同颜色但不透明度不同的对象

问题描述

我有一个包含一组信息的对象,包括颜色。我打算将此颜色实现为具有不透明度的背景颜色和文本颜色(没有不透明度,看起来不同)。

有谁知道我可以如何通过对象/变量的颜色来添加不透明度?

演示

.ts

color: string = "green";
name:string = "ABC";
id: number = 1;

.html

<div style="display: flex; flex-direction: column; width: 60%;">
        <span [style.background-color]="color" [style.color]="color" class="cc">{{name}}</span>
        <span [style.background-color]="color" class="mb" [style.color]="color">{{id}}</span>
    </div>

问题

图片

我希望背景颜色具有不透明度,以便文本可见。我打算实现这一点,而不必创建具有“不同”颜色的变量。

标签: htmlcssangulartypescript

解决方案


您可以在应用不透明度的文本和背景之间添加一个额外的图层:

.box {
  padding:10px;
  display:inline-block;
  color:var(--c);
  background:var(--c);
  position:relative;
  z-index:0;
}

.box::before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:rgba(255, 255, 255, 0.5);
}
<div class="box" style="--c:red">some text</div>

<div class="box" style="--c:blue">some text</div>

<div class="box" style="--c:green">some text</div>

没有伪元素的相同想法:

.box {
  padding:10px;
  display:inline-block;
  color:var(--c);
  background:var(--c);
  
  background-image:linear-gradient(rgba(255, 255, 255, 0.5),rgba(255, 255, 255, 0.5))!important;
}
<div class="box" style="--c:red">some text</div>

<div class="box" style="color:blue;background:blue;">some text</div>

<div class="box" style="color:green;background-color:green;">some text</div>


推荐阅读