Skip to content

Instantly share code, notes, and snippets.

@tedw
Created September 19, 2023 19:15
Show Gist options
  • Save tedw/fc029c1f684f68ac88d52d477ab60920 to your computer and use it in GitHub Desktop.
Save tedw/fc029c1f684f68ac88d52d477ab60920 to your computer and use it in GitHub Desktop.
Generated by SassMeister.com.
/// Convert px to rem
/// @group Main
/// @param {Number | Map} $values - Value values to convert
/// @param {Number} $context [$fs-base-font-size] - Base font size
/// @return {*} - Converted value or list of values
/// @require {variable} $fs-base-font-size - Base font size
@function rem($values) {
// Placeholder list for converted values
$output: ();
@each $val in $values {
// Check if pixel value
@if type-of($val) == 'number' and unit($val) == 'px' {
// Convert to rems
$val: ($val / 16px) * 1rem;
}
// Do nothing to all other values
@else if $debug-mode and $val != 0 {
@warn '⚠️ Can’t convert non-pixel value to rems: #{$val}';
}
// Append value to output list
$output: append($output, $val);
}
// Return converted value(s)
@return $output;
}
/// Generate clamp() to smoothly scale a value between two breakpoints
/// @group Main
/// @param {Map} $map - Map of breakpoints and values
/// @param {String} $units [vw] - Optionally specify container query units
/// @return {String} - Custom `clamp()` formula
/// @require {function} fs-rem
/// @link https://chrisburnell.com/clamp-calculator/
///
/// @example scss
/// p {
/// font-size: scale-clamp((375px: 16px, 960px: 20px));
/// }
///
@function scale-clamp($map, $units: vw) {
// Formulas from link above:
//
// Change = (sizeMax - sizeMin) / (viewportMax - viewportMin);
// A = sizeMax - viewportMax * Change;
// B = 100vw * Change;
// Result = clamp(sizeMin, A + B, sizeMax);
//
$breakpoints: map-keys($map);
$values: map-values($map);
$min-width: nth($breakpoints, 1);
$max-width: nth($breakpoints, 2);
$start: nth($values, 1);
$end: nth($values, 2);
$change: ($end - $start) / ($max-width - $min-width);
$a: $end - ($max-width * $change);
// Add support for container query units
// https://caniuse.com/css-container-query-units
$width: 100vw;
@if $units == 'cqw' {
$width: 100cqw;
} @else if $units == 'cqh' {
$width: 100cqh;
} @else if $units == 'cqi' {
$width: 100cqi;
} @else if $units == 'cqb' {
$width: 100cqb;
}
$b: $width * $change;
// Round to 3 decimal places
// Note: Additional decimal places won’t have any effect on the computed
// value and makes it harder to read in the dev tools.
$a: round($a * 1000) / 1000;
$b: round($b * 1000) / 1000;
@return clamp(#{rem($start)}, #{rem($a)} + #{$b}, #{rem($end)});
}
p {
font-size: scale-clamp((375px: 16px, 1024px: 20px));
}
p {
font-size: clamp(1rem, 0.8555625rem + 0.616vw, 1.25rem);
}
{
"sass": {
"compiler": "dart-sass/1.32.12",
"extensions": {},
"syntax": "SCSS",
"outputStyle": "expanded"
},
"autoprefixer": false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment