Skip to content

Instantly share code, notes, and snippets.

@tillsanders
Last active August 29, 2015 13:58
Show Gist options
  • Save tillsanders/10247766 to your computer and use it in GitHub Desktop.
Save tillsanders/10247766 to your computer and use it in GitHub Desktop.
SCSS: rem-unit mixin

SCSS: rem-unit mixin provides support for older browsers

This mixin was taken from David Walshs Blog (great blog, by the way!); the article was witten by Sébastien Axinté. It provides a mixin to convert rem to px for older browsers.

Link different stylesheets in your head section. main.css for decent browsers and main-ie.css for IE < 9:

<!--[if (gt IE 8) | (IEMobile)]><!-->
      <link rel="stylesheet" href="/css/main.css">
<!--<![endif]-->

<!--[if (lt IE 9) & (!IEMobile)]>
      <link rel="stylesheet" href="/css/main-ie.css">
<![endif]-->

Put this in your main.scss (or equivalent):

$px-only: false !default;
@import "functions";

And this in a new file, called main-ie.scss:

$px-only: true;
@import "main";

Now create a new scss file: _functions.scss:

$pixelBase : 16;
@function parseInt($n) {
	@return $n / ($n * 0 + 1);
}
@function u($values){
      $list: ();
      @each $value in $values {
            $unit : unit($value);
            $val  : parseInt($value);
            @if ($px-only) and ($unit == 'rem') {
                  $list: append($list, ($val * $pixelBase) + px);
            }
            @else if($unit == 'px') or ($unit == 'rem'){
                  $list: append($list, $value);
            }
            @else {
                  @warn 'There is no unit conversion for #{$unit}';
            }
      }
      @return $list();
}

Now, when you use the rem unit, do it like this:

p {
    padding-bottom: u(0.25rem);   
}

Thats it.

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