Skip to content

Instantly share code, notes, and snippets.

@azinasili
Last active August 1, 2023 22:14
Show Gist options
  • Save azinasili/8e41854f58176cbd9cff to your computer and use it in GitHub Desktop.
Save azinasili/8e41854f58176cbd9cff to your computer and use it in GitHub Desktop.
Convert px values to em
// Functions and mixin to convert `px` values into `em` units
//
// px-to-em can easily be changed to `rem` values
// Change any instance of `em` to `rem`
//
// EXAMPLE:
// .foo {
// @include em(margin, 10px auto);
// padding: em(1px 2 3px 4);
// }
// Provide base font-size
$font-size: 16px;
/// Strip unit from number
/// @access private
/// @param {number} $num - Number with unit
/// @return {number} Number without unit
@function _strip-unit($num) {
@return $num / ($num * 0 + 1);
}
/// Convert px to a value for em/rem
/// @access private
/// @param {number} $px - px value to convert
/// @param {number} $base - Context value
/// @require {function} _strip-unit - Strip unit from number
/// @return {number} Unitless converted px
@function _convert-px($px, $base) {
$px: _strip-unit($px);
$font-size: _strip-unit($font-size);
$base-value: _strip-unit($base);
@if unit($base) == 'em' or unit($base) == 'rem' {
$base: ($base-value * $font-size);
} @else {
$base: $base-value;
}
@return ($px / $base);
}
/// Iterate value(s) and convert to em
/// @access public
/// @param {number | list} $values - px value(s) to convert
/// @param {number} $base [$font-size] - em context
/// @require {function} get - Return key value from a map
/// @require {function} _convert-px - Convert px to a value for em/rem
/// @return {number | list} Converted em value(s)
/// @example scss
/// .foo {
/// padding: em(10px 20px);
/// }
/// @example css
/// .foo {
/// padding: .625em 1.25em;
/// }
@function em($values, $base: $font-size) {
$em-values: ();
// Decide how to handle each value
@each $value in $values {
@if type-of($value) != number or unit($value) == 'em' or unit($value) == 'rem' or $value == 0 {
$em-values: append($em-values, $value);
} @else {
$em-value: _convert-px($value, $base) * 1em;
$em-values: append($em-values, $em-value);
}
}
@return $em-values;
}
/// Convert property and px value(s) to em
/// @access public
/// @param {property} $property - Property to convert value(s)
/// @param {number} $values - Value(s) to convert from px to em
/// @param {number} $base [$font-size] - em context
/// @require {function} em - Iterate value(s) and convert to em
/// @output Property and converted em value(s)
/// @example scss
/// .foo {
/// @include em(margin, 10px auto);
/// @include em(padding, 10px);
/// }
/// @example css
/// .foo {
/// margin: .625em auto;
/// padding: .625em;
/// }
@mixin em($property, $values, $base: $font-size) {
#{$property}: em($values, $base);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment