Skip to content

Instantly share code, notes, and snippets.

@thefonso
Created February 5, 2019 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thefonso/ba28fa90655d9cb54f0ae1499063fe86 to your computer and use it in GitHub Desktop.
Save thefonso/ba28fa90655d9cb54f0ae1499063fe86 to your computer and use it in GitHub Desktop.
sass-px-to-em-converter

sass-px-to-em-converter

Diddy SASS helper to generate CSS in EMs when your designers specify pixels:

  // Helper to convert the designers' px specifications into EMs:
  // Eg: H2 { font-size: em(28px); }
  @function em( $px, $basePx: $baseFontPx ) {
    $px:     $px     / ($px     * 0 + 1);   // Strip off units to be sure we have a plain number. (eg: 20px -> 20)
    $basePx: $basePx / ($basePx * 0 + 1);   // Strip off units to be sure we have a plain number. (eg: 20px -> 20)
    @return  $px / $basePx * 1em;           // The *1em ensures we return an EM number.
  }

  $baseFontPx: 16px;

SCSS sample usage:

  H1 {
    font-size: em(32px);
    margin: em(10) em(50);
    SMALL {
      font-size: em(28px,32px);
    }
  }

Resulting CSS:

  H1 {
    font-size: 2em;
    margin: 0.7143em 3.5714em;
  }
  H1 SMALL {
    font-size: 0.875em;
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment