Skip to content

Instantly share code, notes, and snippets.

@ijy
Created December 7, 2011 08:18
Show Gist options
  • Save ijy/1441967 to your computer and use it in GitHub Desktop.
Save ijy/1441967 to your computer and use it in GitHub Desktop.
A Compass function to convert pixel font-sizes to em's
@function em($target, $context: $base-font-size) {
@if $target == 0 { @return 0 }
@return $target / $context + 0em;
}
$base-font-size: 15px;
h1 {
font-size: em(21px, 15px); // Outputs 1.4em
}
@stevenvachon
Copy link

Is there a technical reason why + 0em is used instead of * 1em?

@benjaminhoffman
Copy link

benjaminhoffman commented Sep 13, 2021

Is there a technical reason why + 0em is used instead of * 1em?

@stevenvachon I believe that's an implicit conversion to ensure the result ends up as em

@ob2a
Copy link

ob2a commented Feb 6, 2025

With newest versions of Sass :

@use "sass:math";

@function em($target, $context: $base-font-size) {
  @if $target == 0 {
    @return 0;
  }
  @return math.div($target, $context) * 1em;
}

@function rem($target, $context: $base-font-size) {
  @if $target == 0 {
    @return 0;
  }
  @return math.div($target, $context) * 1rem;
}

$base-font-size: 16px;

html {
    font-size: $base-font-size;
    // Output: font-size: 16px;
}

body {
    font-size: rem(14px, $base-font-size);
    // Output: font-size: 0.875rem;
}

//or
body {
    font-size: rem(14px);
    // Output: font-size: 0.875rem;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment