public
Last active

Sass mixin - rems with px fallback

  • Download Gist
gistfile1.sass
Sass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
// This mixin outputs a property with rem units and a px fallback.
// Values passed without units are used as multipliers for the final
// rem and px values, all other units are output without modification.
// $unit-default-px represents the root value of the document font-size
// in pixels.
//
// i.e. html { font-size: 100%;} // -> 16px
 
// Usage:
// @include px-and-rem([property], [multiplier | explicit value] [, ...]);
 
// Example 1:
//
// $unit-default-px: 16px;
//
// .margin { @include px-and-rem(margin, 2);}
//
// becomes
//
// .margin {
// margin: 32px;
// margin: 2rem;
// }
 
// Example 2:
//
// $unit-default-px: 16px;
//
// .padding { @include px-and-rem(padding, 1, 2%, 1.5em);}
//
// becomes
//
// .padding {
// padding: 16px 2% 1.5em;
// padding: 1rem 2% 1.5em;
// }
 
@function fix8_unit_to_px($val) {
@if unitless($val) {
@if $val == 0 { @return $val}
@else { @return $val * $unit-default-px};
} @else { @return $val};
}
 
@function fix8_unit_to_rem($val) {
@if unitless($val) {
@if $val == 0 { @return $val}
@else { @return $val+rem};
} @else { @return $val};
}
 
@mixin px-and-rem($prop, $val...) {
$n: length($val);
$i: 1;
 
$px-list: ();
$rem-list: ();
 
@while $i <= $n {
$px-list: append($px-list, fix8_unit_to_px(nth($val, $i)));
$rem-list: append($rem-list, fix8_unit_to_rem(nth($val, $i)));
$i: $i + 1;
}
 
#{$prop}: $px-list;
#{$prop}: $rem-list;
}

Thanks to @joelhans for the addition for handling the auto value: SASS + mixins + rems = awesome

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.