Skip to content

Instantly share code, notes, and snippets.

@ogbaoghene
Last active August 29, 2015 14:02
Show Gist options
  • Save ogbaoghene/20222a08fcab548f5593 to your computer and use it in GitHub Desktop.
Save ogbaoghene/20222a08fcab548f5593 to your computer and use it in GitHub Desktop.
Convert px values for multiple property-values pairs to rem values with px fallbacks.
// ----
// Sass (v3.3.8)
// Compass (v1.0.0.alpha.19)
// ----
$baseFontSize: 16;
@function stripUnit ($num) {
@return $num / ($num * 0 + 1);
}
@function pxToRem($values) {
$list: ();
@each $value in $values {
@if $value == 0 or $value == auto or unit($value) != px and unitless($value) != true {
// Ignore 0, auto, and units except px
$list: append($list, $value);
}
@else {
$remValue: ( stripUnit($value) / stripUnit($baseFontSize) ) * 1rem;
$list: append($list, $remValue);
}
}
@if length($list) == 1 {
// return a single value instead of a list,
// so it can be used in calculations
@return nth($list, 1);
}
@else {
@return $list;
}
}
@mixin remFallback($properties) {
@each $property, $value in $properties {
@if type-of($value) == list {
#{$property}: $value;
#{$property}: pxToRem($value);
}
@else if $value == 0 or $value == auto or unit($value) != px and unitless($value) != true {
// Filter values to avoid errors
#{$property}: $value;
}
@else {
#{$property}: $value;
#{$property}: pxToRem($value);
}
}
}
.example {
@include remFallback((
height: 240 / 2,
font-size: 13px,
text-indent: 0,
left: auto,
margin: 0 10px 3vh 30%
));
}
@ogbaoghene
Copy link
Author

Libsass doesn't support @each multiple assignments yet, which causes errors on compilation. I discovered a workaround [here](After finding this [issue]%28sass/node-sass#263, I discovered that I can). Adjust the mixin to pass each property:value pair as an item before isolating the $property and $value variables to allow Libsass compile successfully.

@mixin remFallback($properties) {
  @each $val in $properties {
    $property: nth($val, 1);
    $value: nth($val, 2);
    @if type-of($value) == list {
      #{$property}: $value;
      #{$property}: pxToRem($value);
    }
    @else if $value == 0 or $value == auto or unit($value) != px and unitless($value) != true {
      #{$property}: $value;
    }
    @else {
      #{$property}: $value;
      #{$property}: pxToRem($value);
    }
  }
}

Also, had to change the @include statement to reflect this.

.example {
  @include remFallback((
    (height, (240 / 2)),
    (font-size, 13px),
    (text-indent, 0),
    (left, auto),
    (margin, 0 10px 3vh 30%)
  ));
}

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