Home > Net >  Make SCSS background the same color, but transparent
Make SCSS background the same color, but transparent

Time:07-05

I'm making my own SCSS framework for colors, borders and such.

I'm trying to create a class which would make the current background color of an element more transparent. The color would be set like this:

$bg-red: FF0000;

.bg-red {
   background: $bg-red
}

I wonder if there is a way to add a class that could take the current background and just make it a bit more transparent, without rewriting the color everytime, because I would be dealing with hundreads of colors, something like this:

.bg-transparent-50{
   background: (currentBackground,  opacity: 50%)
}

I know I'm not using the right syntax but this is just for the sake of explanation of what I'm looking for, anyone know the answer to this?

CodePudding user response:

There is no dedicated CSS property (like 'background-opacity').

You can simulate the effect with a background-image defined as a linear gradient over rgba values (ie. color tuples with transparency) on top of the background.

The gradient effect is cancelled by specifying a point interval:

.bg-red {
    background: red;
}
.bg-transparent-50 {
    background-image: linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5));
}
 
<p>
    <div                    style="width: 200px; height: 50px;">Opaque background</div>
    <div  style="width: 200px; height: 50px;">Semi-transparent background</div>
</p>

CodePudding user response:

I would just use rgba in combination with CSS properties.

div {
  padding: 0.25rem 0.5rem;
}

.background {
  --background-opacity: 100;
  background-color: rgba(var(--background-color), var(--background-opacity));
}

.background.black {
  --background-color: 0, 0, 0;
}

.opacity-100 {
  --background-opacity: 0;
}

.opacity-80 {
  --background-opacity: 0.2;
}

.opacity-60 {
  --background-opacity: 0.4;
}

.opacity-40 {
  --background-opacity: 0.6;
}

.opacity-20 {
  --background-opacity: 0.8;
}
<div > 100% opacity </div>
<div > 80% </div>
<div > 60% </div>
<div > 40% </div>
<div > 20% </div>

  • Related