TIL math module in SASS!
POSTED ON:
Today I learned that SASS has a math module.
https://sass-lang.com/documentation/modules/math
@use "sass:math";
@function px2em($px, $metric: 'em', $base-font-size: 16px) {
@if unitless($px) {
@warn "Assuming #{$px} to be in pixels, attempting to convert it into pixels.";
@return px2em($px * 1px, $metric, $base-font-size);
} @else if unit($px) == em {
@return $px;
}
$test: #{math.div($px, $base-font-size) + $metric};
@return $test;
}
This says: divide the $px
and the $base-font-size
, then add the $metric
to it.
Another example:
@use "sass:math";
$container-width: 800px;
$gutter-width: 20px;
$column-count: 4;
$column-width: math.div((($container-width - ($gutter-width * ($column-count - 1))) / $column-count), 1px);
.column {
width: $column-width;
margin-right: $gutter-width;
&:last-child {
margin-right: 0;
}
}
math.div is currently only supported in Dart Sass (sass on npm) >=1.33.0 and not supported in Ruby Sass or LibSass (node-sass on npm).
via https://stackoverflow.com/a/67734107/4096078
One last thing #
To be honest, this looks like spicy garbage.
I can find a few use-cases to use this. But maybe this is where web components, Javascript, or some decoupling would be a better fit than trying to turn SCSS into something it shouldn't be doing.
REF:
https://sass-lang.com/documentation/modules/math
Related TILs
Tagged: sass