Skip to content

Instantly share code, notes, and snippets.

@nDmitry
Last active January 3, 2017 13:26
Show Gist options
  • Save nDmitry/6248185 to your computer and use it in GitHub Desktop.
Save nDmitry/6248185 to your computer and use it in GitHub Desktop.
Stylus mixin for rem units with fallback.
/**
* rem with fallback to px
*
* Use px as unit and only within a property.
* Default root font-size is standard 16px.
*
* Example:
* p {
* font-size: rem(18px);
* box-shadow: 0 0 rem(7px) #000;
* }
* Output:
* p {
* font-size: 18px;
* font-size: 1.125em;
* box-shadow: 0 0 7px #000;
* box-shadow: 0 0 0.4375rem #000;
* }
*/
rem(n, root = 16px) {
unless current-property {
error('rem() must be used within a property');
}
unless unit(n) is 'px' and unit(root) is 'px' {
error('Please use px as unit');
}
replace(expr, str, val) {
expr = clone(expr);
for e, i in expr {
if str == e {
expr[i] = val;
}
}
return expr;
}
add-property(current-property[0], replace(current-property[1], '__CALL__', n));
unit(round((n / root), 3), s('rem'));
}
.test {
font-size: rem(18px);
width: rem(400px);
box-shadow: 0 0 rem(7px) rgba(0, 0, 0, .1);
}
@nDmitry
Copy link
Author

nDmitry commented Aug 16, 2013

Output:

.test {
  font-size: 18px;
  font-size: 1.125rem;
  width: 400px;
  width: 25rem;
  box-shadow: 0 0 7px rgba(0,0,0,0.1);
  box-shadow: 0 0 0.438rem rgba(0,0,0,0.1);
}

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