Sass/Compass - Convert Hex, RGB, or Named Color to RGBA

Pat Newell picture Pat Newell · Feb 14, 2012 · Viewed 57.6k times · Source

This may be Compass 101, but has anyone written a mixin which sets the alpha value of a color? Ideally, I would like the mixin to take any form of color definition, and apply transparency:

@include set-alpha( red, 0.5 );          //prints rgba(255, 0, 0, 0.5);
@include set-alpha( #ff0000, 0.5 );      //prints rgba(255, 0, 0, 0.5);
@include set-alpha( rgb(255,0,0), 0.5 ); //prints rgba(255, 0, 0, 0.5);

Answer

maxbeatty picture maxbeatty · Feb 14, 2012

Use the rgba function built into Sass

Sets the opacity of a color.

Examples:

rgba(#102030, 0.5) => rgba(16, 32, 48, 0.5)
rgba(blue, 0.2) => rgba(0, 0, 255, 0.2)

Parameters:
(Color) color
(Number) alpha — A number between 0 and 1

Returns:
(Color)

Code:

rgba(#ff0000, 0.5); // Output is rgba(255,0,0,0.5);