Skip to content

Instantly share code, notes, and snippets.

@certainlyakey
Last active July 25, 2024 03:37
Show Gist options
  • Save certainlyakey/e9c0d8f5c87ff47e3d5b to your computer and use it in GitHub Desktop.
Save certainlyakey/e9c0d8f5c87ff47e3d5b to your computer and use it in GitHub Desktop.
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:unquote("#{$hex}");
}
$string: '%23' + $string;
@return $string;
}
@jacobdubail
Copy link

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

@seuck
Copy link

seuck commented Dec 29, 2017

I had the same problem as jacobdubail. Thanks!

@keeperofkeys
Copy link

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

@radube
Copy link

radube commented Jun 14, 2018

Exactly what I was looking for, thanks!

@weberjacob
Copy link

Awesome. Thank you.

@cor
Copy link

cor commented Jul 8, 2019

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

@iamnimnul
Copy link

👍

@zetorama
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;
}

// TESTS
$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