Skip to content

Instantly share code, notes, and snippets.

@chrisross
Last active March 3, 2016 11:53
Show Gist options
  • Save chrisross/5936075 to your computer and use it in GitHub Desktop.
Save chrisross/5936075 to your computer and use it in GitHub Desktop.
This Sass extension adds the ability to strip or append units to a number with ease, which can be annoying in Sass. Strip units works on all unit values, eg. 12in, 0.56pt, 800px, 34em, except % but that is already easy to add to unitless numbers.
#!/usr/bin/env ruby
# To implement extension, run this command in a shell:
# $ sass -i -r ./units_sass_extension.rb
# Or require it in compass config
# require './units_sass_extension'
module Sass::Script::Functions
#
# Strips units from a value, e.g. '10px' or '10in' becomes 10
# @param number [Number] Number is a subclass of Sass::Script::Literal
#
# @return [Number]
def strip_units number
assert_type number, :Number
Sass::Script::Number.new number.value.to_f
end
declare :strip_units, :args => [:number]
#
# Appends units to a number, e.g. 10px or 10in
# @param number [Number] Number is a subclass of Sass::Script::Literal
#
# @return [String]
def append_units number, units
assert_type number, :Number
assert_type units, :String
number = "#{strip_units(number).value}#{units}"
Sass::Script::Parser.new(number, 0, 0).parse
end
declare :append_units, :args => [:number, :string]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment