Skip to content

Instantly share code, notes, and snippets.

@certainlyakey
Last active March 5, 2024 16:40
Show Gist options
  • Star 35 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • 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;
}
@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