Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
URL-encode color SASS function / convert color to hex SASS function
//does not work with colors containing alpha
@function encodecolor($string) {
@if type-of($string) == 'color' {
$hex: str-slice(ie-hex-str($string), 4);
$string: '%23' + $string;
@return $string;
Copy link

just saved me so much work. fixed an issue in firefox where the svg wouldn't appear as a background.

Copy link

seuck commented Dec 29, 2017

I had the same problem as jacobdubail. Thanks!

Copy link

This wasn't working properly for me. I have forked it and added a couple of fixes.

Copy link

radube commented Jun 14, 2018

Exactly what I was looking for, thanks!

Copy link

Awesome. Thank you.

Copy link

cor commented Jul 8, 2019

Thanks so much! I also had the same problem as jacobdubail.

Copy link


Copy link

Thanks, that's very useful 👍

does not work with colors containing alpha

Here's a little improvement, accounting just for that — makes it more convenient to use variables:

@function encodecolor($string) {
  @if type-of($string) == 'color' and str-index(#{$string}, '#') == 1 {
    $hex: str-slice(ie-hex-str($string), 4);
    $string: unquote('#{$hex}');

    @return '%23' + $string;

  @return $string;

$test-key-color: cyan;
$test-hex-color: #1ef;
$test-hsl-color: hsl(184, 100%, 53%);
$test-rgb-color:  #11eeff;
$test-rgba-color: rgba(17, 238, 255, 0.69);

@debug encodecolor($test-key-color);  // cyan
@debug encodecolor($test-hex-color);  // %2311EEFF
@debug encodecolor($test-hsl-color);  // %230FEFFF
@debug encodecolor($test-rgb-color);  // %2311EEFF
@debug encodecolor($test-rgba-color);  // rgba(17, 238, 255, 0.69)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment