Skip to content

Instantly share code, notes, and snippets.

@j4k
Created September 3, 2014 11:57
Show Gist options
  • Select an option

  • Save j4k/5b98f42be8595648598b to your computer and use it in GitHub Desktop.

Select an option

Save j4k/5b98f42be8595648598b to your computer and use it in GitHub Desktop.
px2em
// ========== PX to EM calculation
// It strips the unit of measure and returns it
@function strip-unit($num) {
@return $num / ($num * 0 + 1);
}
// Converts "px" to "em" using the ($)em-base
@function convert-to-em($value) {
$value: strip-unit($value) / strip-unit($font-size) * 1em;
@if ($value == 0em) { $value: 0; } // Turn 0em into 0
@return $value;
}
// Working in ems is annoying. Think in pixels by using this handy function, emCalc(#). Just enter the number, no need to mention "px"
@function emCalc($values...) {
$max: length($values); /* Get the total number of parameters passed */
// If there is only 1 parameter, then return it as an integer. This is done because a list can't be multiplied or divided even if it contains a single value
@if $max == 1 { @return convert-to-em(nth($values, 1)); }
$emValues: (); // This will eventually store the converted $values in a list
@for $i from 1 through $max {
$emValues: append($emValues, convert-to-em(nth($values, $i)));
}
@return $emValues;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment