Last active
December 3, 2024 13:11
-
-
Save npostulart/4de142bf2874c1802a15 to your computer and use it in GitHub Desktop.
Unit Converting Sass Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---- | |
// 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 */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool! Thanks for sharing!