Skip to content

Instantly share code, notes, and snippets.

@bruce
Created September 4, 2011 00:35
Show Gist options
  • Save bruce/1192019 to your computer and use it in GitHub Desktop.
Save bruce/1192019 to your computer and use it in GitHub Desktop.
Color Fallbacks
// Mixin that uses the format-color function to create a color fallback for a property
@mixin color-fallback($property, $hsla-color) {
#{$property}: format-color($hsla-color, hex);
#{$property}: format-color($hsla-color, rgb);
#{$property}: format-color($hsla-color, rgba);
#{$property}: format-color($hsla-color, hsl);
#{$property}: format-color($hsla-color, hsla);
}
@import "color-fallback";
body {
@include color-fallback(color, hsla(0, 0%, 15%, 1));
}
# Custom Sass function
module Sass::Script::Functions
def format_color(color, format)
assert_type color, :Color
assert_type format, :String
result = case format.value
when 'hsla'
"hsla(%d, %d%%, %d%%, %f)" % (color.hsl + [color.alpha])
when 'hsl'
"hsl(%d, %d%%, %d%%)" % color.hsl
when 'rgba'
"rgba(%d, %d, %d, %f)" % (color.rgb + [color.alpha])
when 'rgb'
"rgb(%d, %d, %d)" % color.rgb
when 'hex' # really just rgb
"#%s" % color.rgb.map { |c| c.to_s(16) }.join('')
end
Sass::Script::String.new(result)
end
declare :format_color, :args => [:string]
end
body {
color: #262626;
color: rgb(38, 38, 38);
color: rgba(38, 38, 38, 1.000000);
color: hsl(0, 0%, 15%);
color: hsla(0, 0%, 15%, 1.000000); }
@bruce
Copy link
Author

bruce commented Sep 4, 2011

Tested with:

% sass -r ./format_color_function.rb example.scss > result.css

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