How to create CSS Variables with SCSS for a Perfect Fourth type scale

Photograph of typeset blocks

I was recently working through Learn Eleventy From Scratch by Andy Bell which I highly recommend, where he mentioned the use of type scales. Specifically a Perfect Fourth scale. This got me thinking whether there was a simple way to automate the creation of CSS Variables via SCSS for using type scales in my own projects.

After some Googling I came across an older post on Rawkblog titled Modular Scale Typography with CSS Variables and Sass. This post turned out to be an excellent starting point for my idea, and it covered some essentials and key considerations to look out for. As such I’d recommend giving it a quick read too.

However I wanted to remove some of the repetition in the code and create a “lazier” solution. What I settled on was using a SCSS for loop to run through the 9 versions of my type scale and calculate the correct sizes to set my CSS Variables at.

So I took a base font size and the fourth scale ratio of 1.333 denoted by their own variables --font-size and --ratio respectively. Then looped through 9 iterations, using the index to define the CSS variable number.

The first iteration would use the base font size as it’s value. However from then on each following iteration would calculate the font size based on the value of the previous iteration multiplied by the ratio value. To achieve this I had to define a value for each previous iteration as I progressed so I had a reference point. If anyone has a more elegant solution for this I would be very interested to hear it.

The end result gave me access to CSS variables from var(--fs--100): 1rem; through to var(--fs--900): 13.288rem; that iterated through the type scale.

See the CodePen example below for reference to the full code.

Some additional thoughts

You could choose any starting font size, or ratio for that matter. There’s a great resource called by Jeremey Church that will help quickly illustrate different type scales for you based on various common ratios.

To make this scale a bit more flexible you could write a media query to update the --font-size variable for larger screen sizes as required. You could event change the ratio at different screen sizes if that is of benefit as well.

Return to all articles