Stylus PX to REM Mixin
The REM
unit is the hottest thing since Christina Ricci ... it's hot. And it's especially hot when it comes to font size. Rather than paraphrase a bunch of documentation as to why REM is important, I'd like to point you to Jonathan Snook's outstanding Font sizing with rem post, where he explains sizing with PX
, EM
, and how REM
comes into the picture. Here's how I implemented REM
sizing within Stylus with a PX
fallback!
The Stylus CSS
My method uses two mixins to accomplish the feat: one to set the base font-size
and another to rem-ify the pixel unit:
set-font-size(value) { font-size: value; /* add PX (or original value) as backup */ if (value is inherit) { /* do nothing, "inherit" has no unit */ } else { font-size: remify(value); } } remify(value) { /* separate mixin, so it can be used elsewhere */ u = unit(value); if (u is 'px') { return unit(value/16, 'rem'); } else { return unit(value, u); } }
The 16
within the remify
unit represents the base font size, in pixels, that rems should be calculated by. The usage and output looks as follows:
.smaller { set-font-size(13px); } /* yields: .smaller { font-size: 13px; font-size: .8125rem; } */
Don't forget to set the base font size on the html
element, usually 100%
. Also remember this mixin assumes a PX
font is passed in, so if you aren't looking to use PX
as backup, this isn't the solution for you. If you do, however, there's no hurt in using these Stylus mixins!
You can also use this REM converter, which is really nice! https://offroadcode.com/prototypes/rem-calculator/
I’ve been doing it px-ify style instead of remify!
Here’s a rem calculator:
http://codepen.io/dbox/pen/YXQYzR
The first sentence in this post cracks me up every time. Oh and if anyone wants to remify multiple values you can just:
so
yields:
It’s best to let this code work with multi/mixed-values:
Usage: