Created
January 9, 2014 20:34
-
-
Save bubbleheadinc/8341501 to your computer and use it in GitHub Desktop.
SCSS mixin for element sizing in rem's with px fallback
This file contains hidden or 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
// Adapted from: https://gist.github.com/webgefrickel/4530526 | |
// Added if input value is rem output and provide px fallback | |
/* | |
* a small mixin for easy use of rem with px as fallback | |
* usage: @include x-rem(font-size, 14px) | |
* usage: @include x-rem(marign, 0 12px 2 1.2) | |
* usage: @include x-rem(padding, 1.5 24px) | |
* | |
* thanks to Eric Meyer for https://github.com/ericam/susy | |
* and Hans Christian Reinl for http://drublic.de/blog/rem-fallback-sass-less/ | |
*/ | |
@mixin x-rem($property, $values) { | |
// Create a couple of empty lists as output buffers. | |
//$base-font-size: 16px; // should be consistent with your html/body font-size | |
$px-values: (); | |
$rem-values: (); | |
// Loop through the $values list | |
@each $value in $values { | |
// For each property value, if it's in rem or px, derive both rem and | |
// px values for it and add those to the end of the appropriate buffer. | |
// Ensure all pixel values are rounded to the nearest pixel. | |
@if $value == 0 or $value == 0px { | |
// 0 -- use it without a unit | |
$px-values: join($px-values, 0); | |
$rem-values: join($rem-values, 0); | |
} @else if type-of($value) == number and not unitless($value) and (unit($value) == px) { | |
// px value given - calculate rem value from base-font-size | |
$new-rem-value: $value / $base-font-size; | |
$px-values: join($px-values, round($value)); | |
$rem-values: join($rem-values, #{$new-rem-value}rem); | |
} @else if type-of($value) == number and not unitless($value) and (unit($value) == rem) { | |
// rem value given - calculate px value from base-font-size and regurgitate rem value | |
$px-values: join($px-values, round(strip-unit($value) * $base-font-size)); | |
$rem-values: join($rem-values, $value); | |
} @else { | |
// unitless value - use those directly as rem and calculate the px-fallback | |
$px-values: join($px-values, round($value * $base-font-size)); | |
$rem-values: join($rem-values, #{$value}rem); | |
} | |
} | |
// output the converted rules | |
#{$property}: $px-values; | |
#{$property}: $rem-values; | |
} | |
// Returns numeric values without a unit of measure. | |
// @see https://github.com/nex3/sass/issues/533#issuecomment-11675408 | |
@function strip-unit($number) { | |
@return $number / ($number * 0 + 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment