Skip to content

Instantly share code, notes, and snippets.

@iamsaief
Last active November 30, 2022 04:05
Show Gist options
  • Save iamsaief/04bcf64f93df9f3ef953232f9679b384 to your computer and use it in GitHub Desktop.
Save iamsaief/04bcf64f93df9f3ef953232f9679b384 to your computer and use it in GitHub Desktop.
Fluid Typography Utility Classes

🎯  Fluid Typography Utility Classes SASS mixin

✨ The idea of fluid typography has been around in application development for a while, but to make this work in the browser, developers had to use a variety of solutions. 

👨‍💻 Depending on the viewport width, fluid typography adjusts nicely between the minimum and maximum value. Typically, it starts at a minimum value and stays constant until a certain screen width point, at which time it starts to rise. When it hits a maximum value at a different screen width, it keeps going with that maximum value.

👨‍🏫  For instance, if we wanted our font size to be between 2em and 3em, where 2em is the minimum size at the smallest viewport width of 320px and 3em is the maximum size at the highest viewport width of 1366px. Then our equation will look like this - font-size: calc(2em + 1 * (100vw - 320px) / 1046);

@media (min-width: 1366px){
  .fluid-h2 {
      font-size: 3em;
  }
}

@media (min-width: 320px){
  .fluid-h2 {
      font-size: calc(2em + 1 * (100vw - 320px) / 1046);
  }
}

.fuild-h2 {
    font-size: 2em;
    font-weight: 600;
    line-height: 1.21;
}
/* Fluid Typography Sass Mixin */
@mixin fluid-type($properties, $min-vw, $max-vw, $min-value, $max-value) {
@each $property in $properties {
#{$property}: $min-value;
}
@media (min-width: $min-vw) {
@each $property in $properties {
#{$property}: calc(
#{$min-value} + #{strip-unit($max-value - $min-value)} * (100vw - #{$min-vw}) / #{strip-unit($max-vw - $min-vw)}
);
}
}
@media (min-width: $max-vw) {
@each $property in $properties {
#{$property}: $max-value;
}
}
}
@function strip-unit($number) {
@if type-of($number) == 'number' and not unitless($number) {
@return $number / ($number * 0 + 1);
}
@return $number;
}
// ($name, $max, $min, $lh, $fw)
$fluidTypography: (
'h1' 4em 3em 1.09 600,
'h2' 3em 2em 1.21 600,
'h3' 2em 1.5em 1.31 600,
'h4' 1.5em 1.25em 1.42 600,
'h5' 1.25em 1.125em 1.5 600,
'h6' 1.125em 1em 1.5 600,
'18' 1.125em 1em 1.56 400,
'16' 1em null 1.62 400,
'14' 0.875em null 1.71 400,
'13' 0.815em null 1.69 400
);
/* Utility Class */
@each $name, $max, $min, $lh, $fw in $fluidTypography {
.fluid-#{$name} {
font-weight: #{$fw};
line-height: #{$lh};
@if $min != null {
@include fluid-type(font-size, 320px, 1366px, $min, $max);
} @else {
font-size: $max;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment