Skip to content

Instantly share code, notes, and snippets.

@morewry
Created May 26, 2014 22:18
Show Gist options
  • Save morewry/2052fa9d5a6fa3aa1ae1 to your computer and use it in GitHub Desktop.
Save morewry/2052fa9d5a6fa3aa1ae1 to your computer and use it in GitHub Desktop.
Sass convert length units
/*
# Convert Units (function)
TODO: Description
*/
// ---------------------------------------
@function convert-units ( $length, $as: rem, $root: 16, $ppi: 96 ) {
$unit: unit($length);
$value: strip-units($length);
$ratio: $value;
$result: $length;
// convert length in
@if $unit == "px" {
// $value: $value;
$ratio: $value / $root;
}
@else if $unit == "em"
or $unit == "rem"
or $unit == "" {
// $ratio: $ratio;
$value: $ratio * $root;
}
@else if $unit == "%" {
$ratio: $ratio / 10;
$value: $ratio * $root;
}
@else if $unit == "pt" {
$value: ($value * $ppi) / 72;
$ratio: $value / $root;
}
@else if $unit == "pc" {
$value: (($value * 12) * $ppi) / 72;
$ratio: $value / $root;
// convert length out
@if $as == "%" {
$result: percentage($ratio);
}
@else if $as == "/" {
$result: $ratio;
}
@else if $as == "px" {
$result: $value * 1px;
}
@else if $as == "em" {
$result: $ratio * 1em;
}
@else if $as == "rem" {
$result: $ratio * 1rem;
}
@else if $as == "pt" {
$result: ($value * 72) / $ppi;
}
@else if $as == "pc" {
$result: (($value * 72) / $ppi) / 12;
}
@return $result;
}
// ---------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment