HomeWeb DevelopmentHexadecimal to rgba Conversion with Sass

Hexadecimal to rgba Conversion with Sass

If you like using hexadecimal number formats over rgb, but also like the ‘a’ in rgba, then you may want to consider using the Sass rgba function.

The function takes two parameters: the first one is the hexadecimal color, the second is the alpha value.

Converting a dark gray hex to rgba black with 50 percent opacity would like this:

background-color: rgba(#333333, 0.5);

That Sass line will compile to this in CSS:

background-color: rgba(51, 51, 51, 0.5);

Pretty simple, but you can it take one step further and create a mixin that provides a hex fallback.

First create a mixin with one parameter for color, and one for opacity:

@mixin rgba-background($hexcolor, $opacity) {
  background-color: $hexcolor;
  background-color: rgba($hexcolor, $opacity); 

Then call the mixin and pass your desired color and opacity:

@include rgba-background(#333333, 0.5);

That Sass will compile into this:

background-color: #333333;
background-color: rgba(51, 51, 51, 0.5);

I like creating my rgba colors in this fashion for a few reasons. It is quick and easy to implement, it allows me to think in hexadecimal, I can copy from one field in Photoshop(or whatever graphics program), and it results in writing less code if you have several cases where you’d use rgba with a hex fallback.

Here’s the Sass documentation if you’d like to take a look.

My Google+ Account