You can add an extra layer between the text and background where you apply the opacity:
.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>
Same idea without pseudo element:
.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>
You can use the color NPM package to do that:
import Color from 'color';
const colorWithOpacity = Color(yourColor).alpha(yourOpacity).rgb().string();
You will need to adjust your code to pass colorWithOpacity
to your styles.
I have an object with a set of information, including color. I intend this color to be implemented as a background-color with opacity and as a text color (without opacity to look different).
Does anyone know how I can make it so that through the color of the object / variable, I can add opacity?
DEMO
.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>
Problem

I want the background-color to have opacity so that the text is visible. I intend to achieve this, without having to create a variable with a “different” color.
Your question is not clear enough, where do you want this opacity to come from? What is your expected result?