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

Get in Touch


Get in Touch

[td_block_social_counter facebook="tagdiv" style="style6 td-social-boxed" open_in_new_window="y" f_counters_font_family="394" f_network_font_family="891" f_counters_font_size="eyJhbGwiOiIxNCIsImxhbmRzY2FwZSI6IjEzIiwicG9ydHJhaXQiOiIxMiJ9" f_network_font_size="eyJhbGwiOiIxMyIsImxhbmRzY2FwZSI6IjExIiwicG9ydHJhaXQiOiI5In0=" counter_color="#ffffff" counter_color_h="#ffffff" network_color="#ffffff" network_color_h="#ffffff" tdc_css="eyJsYW5kc2NhcGUiOnsibWFyZ2luLWJvdHRvbSI6IjMwIiwiZGlzcGxheSI6IiJ9LCJsYW5kc2NhcGVfbWF4X3dpZHRoIjoxMTQwLCJsYW5kc2NhcGVfbWluX3dpZHRoIjoxMDE5LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMjAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3NjgsInBob25lIjp7Im1hcmdpbi1ib3R0b20iOiI0MCIsImRpc3BsYXkiOiIifSwicGhvbmVfbWF4X3dpZHRoIjo3NjcsImFsbCI6eyJtYXJnaW4tYm90dG9tIjoiNDAiLCJkaXNwbGF5IjoiIn19" twitter="tagdivofficial" youtube="tagdiv"]

Latest Posts