Back to blog

Handling Typography Scale Using SASS

We'll first need to calculate the base to the exponent power of every heading using sass-math-pow

npm install -D sass-math-pow

Then just import it in your .scss/sass file.

@import "~sass-math-pow/sass/math-pow";

Now lets add a few variables to make this easy to edit, we are gonna use these settings:

$typographyScaleRatio: 1.2;
$baseFontSize: 14;

And then lets do the math inside a mixin so we can reuse it later, maybe to add different sizes per screen size:

/**
 * em function
 * Converts px to em.
 */
@function em($pixels, $context: $baseFontSize) {
	@return #{ $pixels / $context }em;
}

// Headings sizes mixin.
@mixin headingsSizes($base) {
	@for $n from 1 through 6 {
		// Convert 1 to 6, 2 to 5, etc.
		$reverseN: 6 - $n + 1; // ArrayLength-n+1

		h#{$n},
		.h#{$n} {
			font-size: em(poly-pow($typographyScaleRatio, $reverseN) * $base); // (ratio^n)*base
		}
	}
}

I added a em mixin that converts the px values to em. I like to add .h(1-6) classes so I can use them later to style elements that are not headings to get the same sizes.

Remember to use the $baseFontSize variable in the body font-size property.

To use it you would just call the mixin:

@include headingsSizes($baseFontSize);

Here is how you would use it with different screen sizes: