Skip to content

Instantly share code, notes, and snippets.

@alex-boom
Last active June 14, 2021 15:08
Show Gist options
  • Save alex-boom/783431080d771885852d83f8db34643a to your computer and use it in GitHub Desktop.
Save alex-boom/783431080d771885852d83f8db34643a to your computer and use it in GitHub Desktop.
Mixin-rem-calc
/// Mixin rem-calc for converting px units into rem units
/// @example scss - Usage
/// .element {
/// font-size: rem-calc(20);
/// }
///
/// @example css - CSS Output
/// .element {
/// font-size: 1.25rem;
/// }
/// Removes the unit (e.g. px, em, rem) from a value, returning the number only.
///
/// @param {Number} $num - Number to strip unit from.
///
/// @returns {Number} The same number, sans unit.
@function strip-unit($num) {
@return $num / ($num * 0 + 1);
}
/// Converts one or more pixel values into matching rem values.
///
/// @param {Number|List} $values - One or more values to convert. Be sure to separate them with spaces and not commas. If you need to convert a comma-separated list, wrap the list in parentheses.
/// @param {Number} $base [$rem-base] - The base value to use when calculating the `rem`. If you're using Foundation out of the box, this is 16px.
///
/// @returns {List} A list of converted values.
@function rem-calc($values, $base: $rem-base) {
$rem-values: ();
$count: length($values);
@if $base == null {
$base: $rem-base;
}
@if $count == 1 {
@return -zf-to-rem($values, $base);
}
@for $i from 1 through $count {
$rem-values: append($rem-values, -zf-to-rem(nth($values, $i), $base));
}
@return $rem-values;
}
/// Converts a pixel value to matching rem value. *Any* value passed, regardless of unit, is assumed to be a pixel value. By default, the base pixel value used to calculate the rem value is taken from the `$rem-base` variable.
/// @access private
///
/// @param {Number} $value - Pixel value to convert.
/// @param {Number} $base [$rem-base] - Base for pixel conversion.
///
/// @returns {Number} A number in rems, calculated based on the given value and the base pixel value. rem values are passed through as is.
@function -zf-to-rem($value, $base: $rem-base) {
// Calculate rem if units for $value is not rem
@if (unit($value) != 'rem') {
$value: strip-unit($value) / strip-unit($base) * 1rem;
}
// Turn 0rem into 0
@if ($value == 0rem) { $value: 0; }
@return $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment