Skip to content

Instantly share code, notes, and snippets.

@RainbowArray
Created July 30, 2014 05:22
Show Gist options
  • Save RainbowArray/5e3d9f5a5cf7cd6eaccc to your computer and use it in GitHub Desktop.
Save RainbowArray/5e3d9f5a5cf7cd6eaccc to your computer and use it in GitHub Desktop.
Sass em to px conversion
@function em2px($target, $context: $base-font-size-em) {
@if $target == 0 { @return 0 }
@return ($target / 1em) * ($context / 1em) * 16 + 0px;
}
@RainbowArray
Copy link
Author

I found plenty of Sass functions to convert ems to px, but didn't find any to do the reverse. So here's what I came up with, and it seems to work so far.

This assumes that the context or base font size is defined in em. It also assumes that you're likely setting font-size: 100% on the html element, which in most cases will result in 16px. That won't always be true, so that's one inherent weakness of this function... but that will be pretty rare. So.

This is also likely to get screwed up if you have multiple em declarations nested inside of each other. That's probably a good thing to avoid in general, though.

Anyhow, any suggestions are welcome.

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