Search code examples
csssasscompass-sassrgba

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


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);

Solution

  • 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);