Control font-size and line-height with a single variable

| permalink | css

With Tailwind, you can switch between different font-size and line-height pairings by changing a single class name.

Can we do the same with CSS variables?

Turns out yes you can, with the power of revert-layer.

/* allow font-size/line-height pairs */
@layer {
  ::after {
    --text: initial;
    /* adds font-family to create a valid declaration */
    --text_: var(--text) serif;
    /* apply font-size and line-height */
    font: var(--text_, revert-layer);
    /* revert everything else */

/* assign paired font scale */
p {
  --text: var(--2xl);

/* font scale */
:root {
  --xs: 0.75rem/1rem;
  --sm: 0.875rem/1.25rem;
  --base: 1rem/1.5rem;
  --lg: 1.125rem/1.75rem;
  --xl: 1.25rem/1.75rem;
  --2xl: 1.5rem/2rem;
  --3xl: 1.875rem/2.25rem;
  --4xl: 2.25rem/2.5rem;
  --5xl: 3rem/1;
  --6xl: 3.75rem/1;
  --7xl: 4.5rem/1;
  --8xl: 6rem/1;
  --9xl: 8rem/1;

--text_ is an intermediary variable that adds a dummy font-family to make the font assignment valid.

I'm still not sure if I'd rather control font-size and line-height individually, but this is certainly a nice trick to have in my toolbox.