Pixel to Em Math Using Sass

According to the W3C (and prevailing wisdom), it’s best practice not to use absolute units for screen display when designing for the web. Ethan Marcotte showed us how to do this a few years back using the target ?? context = result formula in Fluid Grids. I always felt a little bit of pride defining my font-sizes, line-heights and margins using ems, but all that CSS math is a real downer. And sometimes there is unavoidable duplication across various style rules. Enter Sass…


I started playing with Sass for the first time today. Sass adds tons of cool programmatic features to CSS to help you keep it DRY. One of its features is mixins. Mixins give you the ability to define reusable styles and properties. After a little monkeying around I came up with this.

$browser-context: 16px; 
@mixin px-to-ems($prop, $pixels, $context: $browser-context) {
   #{$prop}: #{$pixels/$context}em 

It basically uses the target ÷ context = result formula to convert pixel-based values to ems. The first argument is the property name you’re setting. The second argument is the target size in pixels, and the final argument is the context size. The final argument is optional. If you leave it out it uses the default browser context of 16px. You can use it like this???

h1 {
  @include px-to-ems(font-size, 60);
  @include px-to-ems(margin-bottom, 22, 60);

Which will evaluate to.

h1 {  
  font-size: 3.75em;
  margin-bottom: 0.367em; 

…And you didn’t even have to break out your calculator! Now you can save the time that you would be doing all of that pesky em math for more important things—like this.

comments powered by Disqus