Skip to content

Instantly share code, notes, and snippets.

@npostulart
Last active July 18, 2022 14:21
Show Gist options
  • Save npostulart/4de142bf2874c1802a15 to your computer and use it in GitHub Desktop.
Save npostulart/4de142bf2874c1802a15 to your computer and use it in GitHub Desktop.
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 */
}
@hrvojegolcic
Copy link

hrvojegolcic commented Jun 4, 2018

That's great! Thanks a lot for sharing

@beachcomber
Copy link

Thanks for sharing!

@nguyenthanh1205tb
Copy link

Cool! Thanks for sharing!

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