Last active
April 3, 2024 13:07
-
-
Save iamnbutler/84f7e02e37770f280866ac48792e0886 to your computer and use it in GitHub Desktop.
Dynamic Font Sizes for TailwindCSS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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