cibgraphics
3/19/2014 - 2:43 PM

Automatic REM conversion with LESS or SCSS.

Automatic REM conversion with LESS or SCSS.

// Set base font size variable
$font-size: 10px; // can be anything

// Function that strips units from numbers
@function strip-unit($num) {
  @return $num / ($num * 0 + 1);
}

// SCSS Mixin (requires $font-size to be set)
@mixin rem-size($value, $property: font-size) {
  $pxValue: strip-unit($value);
  $baseValue: strip-unit($font-size);
  $remValue: ($pxValue / $baseValue);
  #{$property}: $value; 
  #{$property}: $remValue + rem;
}


// Set relative font-size to root element
body {
  font-size: $font-size;
}

// Actually use the mixin
p {
  @include rem-size(20px);
}

// exports out to 
// p {
//  font-size: 20px;
//  font-size: 2rem;
// }


/////  Alternative Use  /////
div {
  @include rem-size(600px, 'width');
}

// exports out to 
// div {
//  width: 600px;
//  width: 60rem;
// }
// Set base font size variable
@font-size: 10px; // can be anything

// LESS Mixin (requires @font-size to be set)
.rem-size(@value, @property: font-size) {
  @pxValue: unit(@value);
  @baseValue: unit(@font-size);
  @remValue: (@pxValue / @baseValue);
  @{property}: @value; 
  @{property}: unit(@remValue,rem);
}

// Set relative font-size to root element
body {
  font-size: @font-size;
}

// Actually use the mixin
p {
  .rem-size(20px);
}

// exports out to 
// p {
//  font-size: 20px;
//  font-size: 2rem;
// }


/////  Alternative Use  /////
div {
  .rem-size(600px, 'width');
}

// exports out to 
// div {
//  width: 600px;
//  width: 60rem;
// }