Skip to content

Fluid Typography with SASS / CSS Variables

Published on

About 9 days ago, Richard Rutter wrote about a technique to create fluid typography in CSS using calc(). I liked the approach for its simplicity vs other approaches I had seen before.

Richard proposes a simple, hybrid method that uses both rems and viewport units to calculate font sizes. For example:

h2 {
  font-size: calc(0.5rem + 2.5vmin);
}

So, assuming a rem base of 16px, for a 320px wide screen, the font-size will be:

(0.5 × 16) + (320 × 0.025) = 8 + 8 = 16px

For a 768 px wide screen, the font-size will compute to 27px:

(0.5 × 16) + (768 × 0.025) = 8 + 19 = 27px

Reversing the approach

The first thing I wanted to do was to reverse this approach, creating a function where I could provide a desired font size at a particular breakpoint (in this case a desktop breakpoint), and then let calc() handle the rest.

I’m awful at math, but thankfully this turned out to be pretty easy.

Let’s say I want my h1 to be 48px when the viewport is 1200px wide.

Using Richard’s formula, we know that:

(0.5 × 16) + (1200 × $ratio) = 48

8 + (1200 x $ratio) = 48

All we have to do now is figure out that growth ratio:

8 + (1200 x $ratio) = 48

(1200 x $ratio) = 48 - 8

(1200 x $ratio) = 40

$ratio = 40 / 1200

$ratio = 0.03333

Putting it all together, that means:

(0.5 × 16) + (1200 × 0.03333) = 8 + 39.99 = 47.99px

The next step for me was to replace vmin units with vw units, as I found them to be more reliable for what I needed. The end result is:

h1 {
  font-size: calc(0.5rem + 3.3vw);
}

Eventually, I also decided that using 0.5rem as a base gave me very small font sizes in narrow screens, so I ended bumping that up to 1rem .

Shut up and give me the mixin

I put together both a SCSS and a CSS variables version. They could probably be improved in a couple ways, but they are good enough examples of what you can achieve. You can grab them from CodePen:

Join my newsletter and get articles like this delivered straight into your inbox.