Skip to content

Instantly share code, notes, and snippets.

@arnalyse
Created August 11, 2015 12:38
Show Gist options
  • Save arnalyse/2b8476072ded93ee0e01 to your computer and use it in GitHub Desktop.
Save arnalyse/2b8476072ded93ee0e01 to your computer and use it in GitHub Desktop.
Using rem with IE px fallback
// just use remify where appropriate
body
margin: remify(32px 10px 0 24px)
// set output to px
$rem-to-px-conversion: true
@include "module"
@include "module"
/**
* BLOCK: convert rem to pixels for older browsers
*/
@function parseInt($n)
@return $n / ($n * 0 + 1)
$rem-to-px-conversion: false !default
$rem-to-px-base: 16 !default
/**
* converts pixel values to rem and provides a px fallback on a stylesheet base
*
* the sass variable $rem-to-px-conversion defaults to false.
* for older browsers you can override this in a separate stylesheet and
* all values will outputted as is without a conversion.
*
* the conversion base for px to rem conversions can be configuried
* via $rem-to-px-base and defaults to 16 (as in most browsers)
*
* based on work by David Walsh: http://davidwalsh.name/rem-px-browser-function-sass
*
* @param {String} $values One or more px values
* @return {String} values in rem or px, depending on the configuration
*
* @example
* margin: remify(32px 0 24px 0)
* returns: margin: 2rem 0 1.5rem 0
* and for IE: margin: 32px 0 24px 0
*/
@function remify($values)
// sanity-checks
@if not( global-variable-exists(rem-to-px-conversion) )
@error 'Please provide variable named $rem-to-px-conversion'
@if not( global-variable-exists(rem-to-px-base) )
@error 'Please provide variable named $rem-to-px-base'
$list: ()
// there can be CSS attributes with more than one value
@each $value in $values
$unit : unit($value)
$val : parseInt($value)
@if ($rem-to-px-conversion and $unit == 'px') // rem not supported / IE style
$list: append($list, $value)
@else if ($unit == 'px') // conversion to rem
$list: append($list, ($val/$rem-to-px-base) * 1rem)
@else if ($unit == 'em') // conversion to rem
$list: append($list, $val * 1rem)
@else if ($unit == 'rem')
$list: append($list, $val)
@else if ($unit == '') // unitless values, like in 'margin: 0 16px'
$list: append($list, $value)
@else
@warn 'There is currently no unit conversion for #{$unit}'
// do not return single value list - e.g. this makes math operations simpler
@if length($list) == 1
@return nth($list, 1)
@return $list
/**
* ENDBLOCK: convert rem to pixels for older browsers
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment