TailwindCSS: Fluid typography with CSS Clamp
Wait, a Tailwind CSS article? Of course, I just had to jump on the hype train. But seriously. I was skeptical for a long time and still am partly. But after a few weeks, I've been playing around with it a bit more, and I plan to use it more intensively in the future. But that should not be the topic now so quickly back to the headline: Fluid Typography with CSS Clamp.
One point that bothers me about TailwindCSS is how to handle font sizes. In sum, there are just too many jumps that I have to remember, and that a team has to remember. Here, you quickly get a problem with consistency. Is the breakpoint set? Is the breakpoint correct? Are the sizes right? There are many sources of error.
Fortunately, there are ways to simplify the whole thing significantly. Since IE11 support is becoming a less and less common requirement for projects, you can use CSS features like Clamp (Can I use), a pretty powerful CSS property that fits perfectly for this purpose.
Integrating the whole thing into Tailwind CSS is a bit more complicated. The FLUID_VALUE calculation is a more complex calculation that requires more values from the TailwindCSS config. Let's have a look at the whole thing in detail.
This is a part of my Tailwind CSS Config, where I store some global stuff. In our case the typography and screens stuff is relevant.
Here I get my breakpoint values from the tailwind.settings.js file, which are stored there, without unit, as REM values and then convert them to pixels, since I use the breakpoints within TailwindCSS with pixel values.
Let's move on to the most exciting config file. In the tailwind.settings.fontSizes.js file, we assemble our clamp property. First, we get some settings from tailwind.config.js, and then there are two helper functions.
One is calcMulti, where we simply calculate the minimum and maximum font sizes depending on our multiplier. The whole thing happens without units and in REM.
The second helper function clamp assembles our clamp property. Details about this calculation can be found here: Fluid-responsive font-size calculator, where everything is explained quite well.
Our tailwind.config.js then looks like this (shortened version).
Final output
If we look at the whole thing in the DEV tools in the browser, we see the following line of code for our body font (.text-base). This means nothing else than that our body font has a minimum value of: 1.125rem (18px) and a maximum value of 1.25rem (20px). Everything in between is fluid. The minimum value in our example starts at 20rem (320px), and the maximum value is reached at 96rem (1536px). That means the middle value controls everything in between. No more breakpoints are needed. Love it!
The example .text-5xl shows the whole thing with the multiplier 6. In this case, this is my H1.