Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 822
Pat Newell Avatar asked Feb 14 '12 02:02

Pat Newell


People also ask

Should I use hex or RGBA?

RGBA (Red, Green, Blue, Alpha) is used for making a colour transparent. The value for A (alpha) is from 0, completely transparent, to 1 completely opaque. hex, is a more recent quick easy value used exclusively for websites and applications.

Can you convert RGBA to hex?

Converting RGBA to hex with the #rgba or #rrggbbaa notation follows virtually the same process as the opaque counterpart. Since the alpha ( a ) is normally a value between 0 and 1, we need to multiply it by 255, round the result, then convert it to hexadecimal.


2 Answers

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); 
like image 111
maxbeatty Avatar answered Sep 18 '22 00:09

maxbeatty


The rgba function doesn't work on color with no transparency, it returns an hex again. After all, it's not meant to transform hex to rgba, we're just making profit out of hex doesn't allow alpha (yet).

rgba(#fff, 1) // returns #fff 

So, I made al little functions that buils the rgb string. I don't need to deal with transparencies for now.

@function toRGB ($color) {     @return "rgb(" + red($color) + ", " + green($color) + ", " + blue($color)+ ")"; } 
like image 38
Carlos Martínez Avatar answered Sep 17 '22 00:09

Carlos Martínez