Skip to content

Instantly share code, notes, and snippets.

@qxxt
Last active November 1, 2022 15:28
Show Gist options
  • Save qxxt/e66df4451a984b8b53bda7f85883d128 to your computer and use it in GitHub Desktop.
Save qxxt/e66df4451a984b8b53bda7f85883d128 to your computer and use it in GitHub Desktop.
A fluid typography + responsive typography fallback on SASS
@mixin clamp-calc (
$property,
$min-size,
$max-size,
$min-screen-width: 320px,
$max-screen-width: 1280px
) {
$min-screen-width-rem: $min-screen-width / 16px * 1rem;
$max-screen-width-rem: $max-screen-width / 16px * 1rem;
$factor: 1 / ($max-screen-width-rem - $min-screen-width-rem) * ($max-size - $min-size);
$calc-value: unquote("#{$min-size - ($min-screen-width-rem * $factor)} + #{100vw * $factor}");
#{$property}: $min-size;
#{$property}: clamp( $min-size, $calc-value, $max-size );
}
html {
@include clamp-calc(font-size, 1rem, 2rem);
}
/*
Output:
html {
font-size: 1rem;
font-size: clamp(1rem, 0.6666666667rem + 1.6666666667vw, 2rem);
}
*/
@function calc-responsive (
$min-size,
$max-size,
$current-screen-width,
$min-screen-width:320px,
$max-screen-width: 1280px
) {
@if $current-screen-width == $max-screen-width {
@return $max-size;
}
@return ($current-screen-width - $min-screen-width) / ($max-screen-width - $min-screen-width) * ($max-size - $min-size) + $min-size;
}
@supports not (font-size: clamp(1,1,1)) {
@media (min-width: 768px) {
html {
font-size: calc-responsive(1rem, 2rem, 768px);
}
}
@media (min-width: 1024px) {
html {
font-size: calc-responsive(1rem, 2rem, 1024px);
}
}
@media (min-width: 1280px) {
html {
font-size: calc-responsive(1rem, 2rem, 1280px);
}
}
}
/*
Output:
@supports not (font-size: clamp(1, 1, 1)) {
@media (min-width: 768px) {
html {
font-size: 1.4666666667rem;
}
}
@media (min-width: 1024px) {
html {
font-size: 1.7333333333rem;
}
}
@media (min-width: 1280px) {
html {
font-size: 2rem;
}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment