Skip to content

Instantly share code, notes, and snippets.

@larrybotha
Last active April 9, 2018 16:50
Show Gist options
  • Save larrybotha/4153104 to your computer and use it in GitHub Desktop.
Save larrybotha/4153104 to your computer and use it in GitHub Desktop.
Sass mixin - rems with px fallback
// 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.
// $base-font-size 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:
//
// $base-font-size: 16px;
//
// .margin { @include px-and-rem(margin, 2);}
//
// becomes
//
// .margin {
// margin: 32px;
// margin: 2rem;
// }
// Example 2:
//
// $base-font-size: 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_get_px_and_rem_val($val) {
$output: ();
@if type-of($val) == 'string' {
@if $val == 'auto' or $val == '!important' {
$output: join($val, $val);
@return $output;
}
} @else {
@if $val == 0 or $val == 0px {
$output: join(0, 0);
} @else if unitless($val) {
$output: join($val * $base-font-size, $val + rem);
} @else {
$output: join($val, $val);
}
@return $output;
}
@warn "#{$val} is not a valid value";
@return false;
}
@mixin px-and-rem($prop, $vals) {
$px-list: ();
$rem-list: ();
@each $val in $vals {
$calcs: fix8_get_px_and_rem_val($val);
$px-list: append($px-list, nth($calcs, 1));
$rem-list: append($rem-list, nth($calcs, 2));
}
#{$prop}: $px-list;
#{$prop}: $rem-list;
}
@larrybotha
Copy link
Author

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

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