Skip to content

Instantly share code, notes, and snippets.

Embed
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:unquote("#{$hex}");
}
$string: '%23' + $string;
@return $string;
}
@jacobdubail

This comment has been minimized.

Copy link

@jacobdubail jacobdubail commented Apr 21, 2017

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

@seuck

This comment has been minimized.

Copy link

@seuck seuck commented Dec 29, 2017

I had the same problem as jacobdubail. Thanks!

@keeperofkeys

This comment has been minimized.

Copy link

@keeperofkeys keeperofkeys commented Feb 28, 2018

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

@radube

This comment has been minimized.

Copy link

@radube radube commented Jun 14, 2018

Exactly what I was looking for, thanks!

@weberjacob

This comment has been minimized.

Copy link

@weberjacob weberjacob commented Jun 13, 2019

Awesome. Thank you.

@cor

This comment has been minimized.

Copy link

@cor cor commented Jul 8, 2019

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

@iamnimnul

This comment has been minimized.

Copy link

@iamnimnul iamnimnul commented Jul 24, 2019

👍

@zetorama

This comment has been minimized.

Copy link

@zetorama zetorama commented Sep 18, 2020

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