Maxo
Maxo

Reputation: 181

SASS Simple function to convert HEX color into RGB as a string without alpha

I am looking for simple function in SASS that simply convert HEX color into RGB as a string. I was googling, but without lucky. Maybe because there is not any native function in SASS? Sure, there is rgba() function, but I dont wanna rgba( ... ) piece. Simply the RGB string.

Example

Input

$color-bg: #637b9a;
$color-bg-light: lighten($color-bg, 25%);
$color-bg-light-rgb: hex2rgb($color-bg-light); // Functon that I am looking for

:root {
  --color-body-bg-light: $color-bg-light;
  --color-body-bg-light-rgb: $color-bg-light-rgb;
}
body {
  color: var(--color-body-bg-light);
  background-color: rgba(var(--color-body-bg-light-rgb), 0.8);
}

Output

:root {
  --color-body-bg-light: #237b9a;
  --color-body-bg-light-rgb: 44, 123, 154;
}

body {
  color: var(--color-body-bg-light);
  background-color: rgba(var(--color-body-bg-light-rgb), 0.8);
}

Upvotes: 0

Views: 2027

Answers (2)

sfy
sfy

Reputation: 3268

You can write the function like this:

@use "sass:color";
@function hex2rgb($hex) {
  @return red($hex), green($hex), blue($hex);
}

But the problem is sass could not parse the variables for html custom properties. So this line --color-body-bg-light: $color-bg-light; won't work.

At the end, you will get this:

:root {
  --color-body-bg-light: $color-bg-light;
  --color-body-bg-light-rgb: $color-bg-light-rgb;
}

Upvotes: 3

Shounak Das
Shounak Das

Reputation: 565

You can't do that with Sass but you can use JavaScript to get the desired result.

Upvotes: 0

Related Questions