Skip to content

Instantly share code, notes, and snippets.

@doits
Last active November 20, 2015 22:12
Show Gist options
  • Save doits/0e02176e9956b1029963 to your computer and use it in GitHub Desktop.
Save doits/0e02176e9956b1029963 to your computer and use it in GitHub Desktop.
Generated by SassMeister.com.
// ----
// libsass (v3.2.5)
// ----
//
@function strip-units($number) {
@return $number / ($number * 0 + 1);
}
// convert-units function
// by Dariusz Sikorski http://prettyminimal.com
// http://www.dariuszsikorski.pl
// convert any css font-size unit, to other unit
// usage: convert-units( inputValue, outputUnit)
// example: convert-units(32px, rem);
@function convert-units(
$value,
$outputUnit: px
){
// default unit sizes measured in px for 1920x1200 (imac 24') screen
// http://www.w3schools.com/browsers/browsers_display.asp
// http://www.w3schools.com/cssref/css_units.asp
$units: (
px: 1,
em: 16,
ex: 9.12656,
ch: 9.78827,
rem: 16,
vw: 17.4545,
vh: 9.86364,
vmin: 9.86364,
vmax: 17.4545,
%: 0.16,
cm: 37.7953,
mm: 3.77953,
in: 96,
pt: 1.33333,
pc: 16
);
// check if input value is a number
@if type-of($value) == number {
$inputUnit: unit($value);
// define variable for value to px conversion
$pxValue: 1;
// define variable for px to output value conversion
$outputValue: 1px;
// if input value was unitless, convert it to pixels
@if unitless($value){
$value: $value * 1px;
}
// convert input value to px units
// @each Key, Value in Map
@each $keyUnit, $size in $units {
@if $inputUnit == $keyUnit {
$pxValue: strip-units($value) * $size;
}
}
// convert pxValue to output value
@each $keyUnit, $size in $units {
@if $outputUnit == $keyUnit {
// $outputValue: $pxValue;
// $outputValue: $size;
// $outputValue: $outputUnit;
$outputValue: length($pxValue / $size, $outputUnit);
}
}
@return $outputValue;
}
// return communicate when $value is not a number
@return "value must be a number";
}
@function length($number, $unit) {
$strings: 'px' 'cm' 'mm' '%' 'ch' 'pica' 'in' 'em' 'rem' 'pt' 'pc' 'ex' 'vw' 'vh' 'vmin' 'vmax';
$units: 1px 1cm 1mm 1% 1ch 1pica 1in 1em 1rem 1pt 1pc 1ex 1vw 1vh 1vmin 1vmax;
$index: index($strings, $unit);
@if not $index {
@warn "Unknown unit `#{$unit}`.";
@return false;
}
@return $number * nth($units, $index);
}
.test {
$height: 50px;
height: $height;
converted: convert-units($height, rem);
stripped: strip-units($height);
manualConvert: convert-units(50px, rem);
manualStrip: strip-units(3.125rem);
pipe: strip-units( convert-units($height, rem) );
}
.test {
height: 50px;
converted: 3.125rem;
stripped: 50;
manualConvert: 3.125rem;
manualStrip: 3.125;
pipe: 3.125;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment