Skip to content

Instantly share code, notes, and snippets.

@widoz
Last active April 19, 2026 15:16
Show Gist options
  • Select an option

  • Save widoz/db4b0d39669fd3a2cd35f2268f0d5f63 to your computer and use it in GitHub Desktop.

Select an option

Save widoz/db4b0d39669fd3a2cd35f2268f0d5f63 to your computer and use it in GitHub Desktop.
Convert Px to Em and Rem relative units
@use "sass:math";
$browser-context: 16;
/*
* Convert pixels to ems.
*/
@function em($pixels, $context: $browser-context) {
@if (math.is-unitless($pixels)) {
$pixels: $pixels * 1px;
}
@if (math.is-unitless($context)) {
$context: $context * 1px;
}
@return math.div($pixels, $context) * 1em;
}
/*
* Convert pixels to rems.
*/
@function rem($pixels, $context: $browser-context) {
@if (math.is-unitless($pixels)) {
$pixels: $pixels * 1px;
}
@if (math.is-unitless($context)) {
$context: $context * 1px;
}
@return math.div($pixels, $context) * 1rem;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment