Last active
March 14, 2024 16:29
-
-
Save kingkool68/d2da6d3461eb7d47ca5815f9dee2b5f3 to your computer and use it in GitHub Desktop.
Sass function for calculating fluid values using clamp() for padding or font-sizes or anything really. Example: font-size: fluid(16px, 32px) --> font-size: clamp( 1rem, 0.143rem + 2.857vw, 2rem );
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
@use "sass:math"; | |
// via https://css-tricks.com/snippets/sass/px-to-em-functions/ | |
$browser-context: 16; | |
@function rem($pixels) { | |
@if (unitless($pixels)) { | |
$pixels: $pixels * 1px; | |
} | |
$context: $browser-context; | |
@if (unitless($context)) { | |
$context: $context * 1px; | |
} | |
@return math.div($pixels, $context) * 1rem; | |
} | |
/** | |
* Fluid calculation via clamp() | |
* | |
* @via https://www.smashingmagazine.com/2022/10/fluid-typography-clamp-sass-functions/ | |
*/ | |
$default-fluid-min-bp: 480px; | |
$default-fluid-max-bp: 1040px; | |
@function round($number, $decimals: 0) { | |
$n: 1; | |
@if $decimals >0 { | |
@for $i from 1 through $decimals { | |
$n: $n * 10; | |
} | |
} | |
@return math.div(math.round($number * $n), $n); | |
} | |
@function fluid($min-size, $max-size, $min-breakpoint: $default-fluid-min-bp, $max-breakpoint: $default-fluid-max-bp, $unit: vw) { | |
$slope: math.div($max-size - $min-size, $max-breakpoint - $min-breakpoint); | |
$slope-to-unit: round($slope * 100, 3); | |
$intercept-rem: round(rem($min-size - $slope * $min-breakpoint), 3); | |
$min-size-rem: round(rem($min-size), 3); | |
$max-size-rem: round(rem($max-size), 3); | |
@return clamp(#{$min-size-rem}, #{$intercept-rem} + #{$slope-to-unit}#{$unit}, #{$max-size-rem}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment