maxkoshel
1/29/2015 - 8:36 AM

Rem mixin for stylus

Rem mixin for stylus

/**
 * 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.438rem #000;
 * }
 */
rem(n, fallback = true, root = default-font-size) {
  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 a unit');
  }

  replace(expr, str, val) {
    expr = clone(expr);

    for e, i in expr {
      if str == e {
        expr[i] = val;
      }
    }

    return expr;
  }

  if fallback {
    add-property(current-property[0], replace(current-property[1], '__CALL__', n));
  }

  unit(round((n / root), 4), s('rem'));
}