Converting Hex to RGBa for background opacity

I have the following Sass mixin, which is a half complete modification of an RGBa example :

@mixin background-opacity($color, $opacity: .3) {
    background: rgb(200, 54, 54); /* The Fallback */
    background: rgba(200, 54, 54, $opacity);
} 

I have applied $opacity ok, but now I am a stuck with the $color part. The colors I will be sending into the mixin will be HEX not RGB.

My example use will be:

element {
    @include background-opacity(#333, .5);
}

How can I use HEX values within this mixin?


The rgba() function can accept a single hex color as well decimal RGB values. For example, this would work just fine:

@mixin background-opacity($color, $opacity: 0.3) {
    background: $color; /* The Fallback */
    background: rgba($color, $opacity);
}

element {
     @include background-opacity(#333, 0.5);
}

If you ever need to break the hex color into RGB components, though, you can use the red(), green(), and blue() functions to do so:

$red: red($color);
$green: green($color);
$blue: blue($color);

background: rgb($red, $green, $blue); /* same as using "background: $color" */

There is a builtin mixin: transparentize($color, $amount);

background-color: transparentize(#F05353, .3);

The amount should be between 0 to 1;

Official Sass Documentation (Module: Sass::Script::Functions)


SASS has a built-in rgba() function to evaluate values.

rgba($color, $alpha)

Eg

rgba(#00aaff, 0.5) => rgba(0, 170, 255, 0.5)

An example using your own variables:

$my-color: #00aaff;
$my-opacity: 0.5;

.my-element {
  color: rgba($my-color, $my-opacity);
}

Outputs:

.my-element {
  color: rgba(0, 170, 255, 0.5);
}
链接地址: http://www.djcxy.com/p/87542.html

上一篇: CSS中的透明背景颜色来自十六进制RGB值

下一篇: 将十六进制转换为RGBa以获得背景不透明度