Search code examples
sassmaterial-designmaterial-design-lite

SASS HEX to RGB without 'rgb' prefix


The Question:

Is there a SASS function/technique that transforms a HEX value to a simple RGB string.

Simple here meaning just a string without it being enclosed in rgb() ?

E.g: #D50000 --> "213,0,0"


Why I need this:

I'm using Material Design Lite as my UI 'framework'. More specifically I'm using the SASS version so I can tweak the color variables according to my app's style-guide.

For some reason the color variables in _variables.scss of MDL take this format for color definitions:

$color-primary: "0,0,0" !default; // supposed to be black

which is really, really odd. I expected, at most, something along the lines of

$color-primary: rgba(0,0,0,1) !default;

My color variables are stored in another file called _globals.scss in which I store my variables in regular HEX format so I can easily reuse them in other places:

$brand-primary: #FA3166;
$brand-primary-dark: #E02C59;

I don't want to define 2 times my colours (1 HEX & 1 MDL-compatible RGB string), hence the reason I need to transform HEX to RGB-string.


Solution

  • @nicholas-kyriakides's answer works perfectly fine, but here is a more concise function using Sass interpolation.

    @function hexToRGBString($hexColor) {
      @return "#{red($hexColor)},#{green($hexColor)},#{blue($hexColor)}";
    }
    

    You can pass in either a hex either explicity or from rgb() or rgba() with opacity as 1.

    For example:

    $color-white: hexToRGBString(#fff) => "255,255,255"
    $color-white: hexToRGBString(rgb(255,255,255)) => "255,255,255"
    $color-white: hexToRGBString(rgba(#fff,1)) => "255,255,255"