Last active
August 29, 2015 13:57
-
-
Save dropofwill/9534209 to your computer and use it in GitHub Desktop.
Sass mixin to use rem with px backup for older browsers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Set this to your root element's px size | |
$base_px_size: 16; | |
@function strip-unit($num) { | |
@if unitless( $num ) != true { | |
@return $num / ($num * 0 + 1); | |
} | |
@else { | |
@return $num; | |
} | |
} | |
// Takes a property and some rem values | |
// Outputs pixel versions before the rem ones as a backup for browsers that don't support rem | |
// Usage: @include rem( margin, 0, auto, 20, 10 ); | |
@mixin rem($property, $values...) { | |
$length: length($values); | |
$px_values: ''; | |
$rem_values: ''; | |
$the_same: true; | |
@for $i from 1 through $length { | |
// If value is 0 don't output units | |
// 0px == 0 in sass so don't need to test for that case | |
@if nth( $values, $i ) == 0 { | |
$px_values: #{$px_values + 0}; | |
$rem_values: #{$rem_values + 0}; | |
} | |
// If value is a different number output both px and rem versions | |
// This makes the two different | |
@else if type-of( nth( $values, $i ) ) == number { | |
$value: strip-unit( nth( $values, $i ) ); | |
$px_values: #{$px_values + $value * $base_px_size }px; | |
$rem_values: #{$rem_values + $value}rem; | |
$the_same: false; | |
} | |
// If not a number (e.g. auto) just output it | |
@else { | |
$px_values: #{$px_values + nth( $values, $i )}; | |
$rem_values: #{$rem_values + nth( $values, $i )}; | |
} | |
@if $i < $length { | |
$px_values: #{$px_values + " "}; | |
$rem_values: #{$rem_values + " "}; | |
} | |
} | |
@if $the_same == false { | |
#{$property}: $px_values; | |
#{$property}: $rem_values; | |
} | |
@else { | |
#{$property}: $px_values; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment