npostulart
3/11/2015 - 8:37 AM

Unit Converting Sass Function

Unit Converting Sass Function

// ----
// Sass (v3.4.12)
// Compass (v1.0.3)
// ----

$baseSize: 16px;
$convertBase: $baseSize;

html {
  font-size: percentage($baseSize / 16px);
}

@function convert($value, $convertUnit, $convertBase: $convertBase) {
  $currentUnit: unit($value);
  $strippedValue: $value / ($value * 0 + 1);
  @if not unitless($convertBase) {
    @if unit($convertBase) != px {
      @error "Not supported unit '#{unit($convertBase)}' as convert base!";
    }
    $convertBase: $convertBase / ($convertBase * 0 + 1);
  }
  
  @if $currentUnit == px {
    @if $convertUnit == 'em' {
      @return 0em + ($strippedValue / $convertBase);
    }
    @else if $convertUnit == '%' {
      @return percentage($strippedValue / $convertBase);
    }
  }
  @else if $currentUnit == em {
    @if $convertUnit == 'px' {
      @return 0px + ($strippedValue * $convertBase);
    }
    @else if $convertUnit == '%' {
       @return percentage($strippedValue);
    }
  }
  @else if $currentUnit == '%' {
    @if $convertUnit == 'px' {
      @return 0em + ($strippedValue * $convertBase / 100);
    }
    @else if $convertUnit == 'em' {
      @return 0em + ($strippedValue / 100);
    }
  }
  // TODO: Check for pt unit convert
  @else if $currentUnit == pt {
    @if $convertUnit == 'px' {
      @return 0px + ($strippedValue * 1.3333);
    }
    @else if $convertUnit == 'em' {
      @return 0em + ($strippedValue / 12);
    }
    @else if $convertUnit == '%' {
        @return percentage($strippedValue / 12)
    }
  }
  @error "Can't convert '#{$value}' to unit '#{$convertUnit}'!";
}

.example1 {
  font-size: convert(18px, '%'); /* converted from pixels */
}

.example2 {
  font-size: convert(13pt, 'em'); /* converted from points */
}

.example3 {
  font-size: convert(2.5em, 'px'); /* converted from ems */
}

.example4 {
  font-size: convert(234%, 'px'); /* converted from percentage */
}