Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save iamnbutler/84f7e02e37770f280866ac48792e0886 to your computer and use it in GitHub Desktop.
Save iamnbutler/84f7e02e37770f280866ac48792e0886 to your computer and use it in GitHub Desktop.
Dynamic Font Sizes for TailwindCSS
import tailwindTypography from '@tailwindcss/typography';
import { Config } from 'tailwindcss';
import typography from './typography';
const fontKeys = {
xs: 'xs',
sm: 'sm',
base: 'base',
lg: 'lg',
xl: 'xl',
'2xl': '2xl',
'3xl': '3xl',
'4xl': '4xl',
'5xl': '5xl',
'6xl': '6xl',
'7xl': '7xl',
'8xl': '8xl',
'9xl': '9xl',
} as const;
type FontKey = keyof typeof fontKeys;
type FontSize = Record<FontKey, [string, { lineHeight: string }]>;
const objectKeys = <Obj extends Object>(obj: Obj): (keyof Obj)[] => {
return Object.keys(obj) as (keyof Obj)[]
}
/**
* - scale value: a number like 1.125 (Major Second) or 1.25 (Minor Third)
* - baseLineHeight: a number like 1.3, returns rems (body text, small headlines, etc)
* - displayLineHeight a number like 1.3 returns a percent value (used for large headlines)
*/
const generateFontSizes = (scale: number, baseLineHeight: number, displayLineHeight: number): FontSize => {
const keys = objectKeys(fontKeys);
const baseIndex = keys.indexOf('base');
const baseFontSize = 1;
return keys.reduce((fontSizes, key, index) => {
const stepsFromBase = index - baseIndex;
const scaleFactor = Math.pow(scale, Math.abs(stepsFromBase));
const fontSize = (stepsFromBase < 0 ? baseFontSize / scaleFactor : baseFontSize * scaleFactor).toFixed(3) + 'rem';
const lineHeight = (stepsFromBase >= 5 ? displayLineHeight.toString() : (baseLineHeight * scaleFactor).toFixed(3) + 'rem');
fontSizes[key] = [fontSize, { lineHeight }];
return fontSizes;
}, {} as FontSize);
}
const config: Config = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
darkMode: 'class',
plugins: [tailwindTypography],
theme: {
fontSize: generateFontSizes(1.125, 1.5, 1.25),
typography,
},
};
export default config;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment