1. Analyze the Request:
* Goal: Develop a Tailwind CSS plugin for generating custom typography scales.
* Key Features:
* Needs to be a Tailwind plugin (JavaScript API).
* Needs to generate utility classes for typography (likely font-size, line-height, and maybe letter-spacing).
* "Custom typography scales" implies a modular scale (musical ratios like Major Third, Perfect Fourth, Golden Ratio, etc.) or a mathematical calculation based on a base size and a ratio.
* Output: Code for the plugin, usage instructions, and an example configuration.
-
Understand Tailwind CSS Plugin Structure:
- Tailwind plugins use
plugin(function({ matchUtilities, theme, ... }) { ... })).
- I need to expose new utilities, likely under a namespace like
text-scale-{step} or similar.
- I should also consider adding corresponding line-heights to keep vertical rhythm consistent.
-
Determine the Logic of a Typography Scale:
- A typography scale is defined by:
- Base Size (e.g., 16px or 1rem).
- Ratio (e.g., 1.25, 1.333, 1.5, 1.618).
- Steps (integers representing how many times to multiply or divide by the ratio).
- Formula:
baseSize * (ratio ^ step).
- Constraint: CSS
calc() has limitations with exponents. It's often better to pre-calculate these values in JS or use CSS variables. Pre-calculating in the plugin logic is more robust and provides direct pixel/rem values in the CSS output.
-
Drafting the Plugin Architecture:
-
Refining the Code (Mental Iteration 1):
- Input:
theme('typographyScale.base'), theme('typographyScale.ratio').
- Calculation: Loop from minStep to maxStep.
Math.pow(ratio, step) * base.
- Output: An object
{ '1': '1.25rem', '2': '1.563rem', ... }.
- Utilities:
matchUtilities allows dynamic generation.
-
Refining the Code (Mental Iteration 2 - Handling Line Height):
- If I just output a font-size value, the user still has to set line-height manually.
- Ideally, the utility sets
font-size and line-height.
- Tailwind's core
fontSize plugin supports an array format: [size, lineHeight].
- So, if I generate the values in the plugin, I should output them in this format or simply generate CSS rules that target both.
- Let's stick to Tailwind's standard pattern: The utility class applies
font-size. If the value is an array [fontSize, { lineHeight: ... }], Tailwind handles it.
- Actually, a simpler approach for the plugin user is to just calculate the font-size values based on the scale. Line-height preferences vary wildly (unitless vs px vs em). Let's keep the plugin focused on the scale calculation. However, providing an option for line-height is a "nice to have". Let's stick to generating
font-size first, maybe adding a default line-height logic if requested, but keeping it simple is better for a generic plugin.
- Correction: In modern Tailwind,
text-{size} usually handles line height if configured. I will generate the values, and the user can map them. Or, I will make the plugin generate font-size and line-height tuples automatically based on a "leading" calculation? No, that's too opinionated.
- Decision: The plugin will generate the font-sizes. It will allow configuration for base, ratio, and steps. The output will be standard Tailwind values.
-
Drafting the Code (The actual implementation):
const plugin = require('tailwindcss/plugin');
module.exports = plugin(function({ matchUtilities, theme }) {
// 1. Get config
const base = theme('typographyScale.base', 1); // rem
const ratio = theme('typographyScale.ratio', 1.25);
// 2. Calculate values
// ...
// 3. matchUtilities('text', ...)
});
-
Adding "Musical" Ratios Presets:
- It's helpful to include named ratios (Minor Second, Major Third, Golden Ratio) so users don't have to look up floats.
-
Constructing the Final Output:
- Part 1: The Plugin Code.
- Part 2: Configuration Example. (How to put it in
tailwind.config.js).
- Part 3: Usage in HTML.
- Part 4: Explanation of the Math.
-
Self-Correction/Refinement during coding:
- Issue:
matchUtilities expects an object of values.
- Solution: I need to generate that object dynamically within the plugin closure.
- Math:
value = base * Math.pow(ratio, step). Note that negative steps reduce size.
- Naming:
.text-sm, .text-base, .text-lg are already taken by Tailwind defaults.
- New Naming:
.text-scale-0, .text-scale-1, .text-scale-2 (where 0 is base). Or let the user define the keys? No, let's stick to integer steps for a "scale" plugin. e.g., .text-step-{n}.
-
Writing the Code (Mental Check):
- Need
lodash.get or just standard JS? Standard JS theme() is fine.
- Need to handle the return format.
- Wait, Tailwind's
fontSize utility allows passing CSS variables or complex objects. If I want to be fancy, I can output font-size AND line-height.
- Let's output the standard Tailwind format:
[fontSize, lineHeight]. I will include a logic to calculate a basic line-height (larger text needs smaller line-height usually). Or just let the user override.
- Revised Approach: Keep it simple. The plugin generates the sizes. The user decides on line-height. If I force line-height, it might break their layout. However, standard typography scales usually imply a vertical rhythm.
- Compromise: I will provide the code to generate just the sizes, but add a configuration option to enable "auto-line-height" (e.g.,
1.2 for headers, 1.5 for body). Actually, simpler is better: Just generate the pixel/rem values. The user can use leading-{n} alongside it.
-
Final Polish of the Plugin Code:
- Accept
base (default 1rem).
- Accept
ratio (default 1.25).
- Accept
steps (e.g. -2 to 6).
- Generate utility class
text-{step} or text-step-{step}. Let's use text-step-{step} to avoid collisions with native text-sm, text-lg.
Wait, Tailwind's fontSize is text-{size}. If I add values to the theme fontSize, I can use the standard text- prefix.
- The prompt asks for a plugin.
- I will use
addUtilities or matchUtilities.
- If I use
matchUtilities({ 'text-step': values }), I get classes like text-step-1.
- This is cleaner and separates "Scale" from "Arbitrary sizes".
-
Implementation Details:
- Use
matchUtilities.
- Value generator function.
- Configuration object.
-
Checking Edge Cases:
- Unitless base? Assume
rem.
- String base "16px"? Parse logic gets complex.
- Assumption: Base is usually
1 (meaning 1rem or 16px depending on root). Let's assume rem.
-
Reviewing the Output Structure:
- Create
typographyScalePlugin.js.
- Show
tailwind.config.js.
- Show HTML.
Let's write the actual JS code in the response.
Code logic:
matchUtilities(
{
'text-scale': (value) => ({
fontSize: value,
// Optional: dynamic line height logic could go here
// e.g. if size > 2rem, lineHeight: 1.1
}),
},
{
values: theme('typographyScale'), // where we calculate the map
}
)
Actually, pre-calculating the values map is easier.
Map: { 'sm': '0.8rem', 'base': '1rem', 'lg': '1.25rem' } -> No, scales are usually steps.
Map: { '-1': '0.8rem', '0': '1rem', '1': '1.25rem' }
Let's refine the "Auto Line Height" idea. It's a killer feature. If the text is big (>4rem), line height should be tight. If it's body text, it's loose.
For this specific request, I will stick to the Core Requirement: "Generating custom typography scales" (the math part). I'll add a comment on how to expand it to line-height.
Self-Correction: The user wants a complete solution. I should make the plugin extend Tailwind's default fontSize or create a new namespace. Creating a new namespace text-step is safer so it doesn't override defaults unless intended.
Let's proceed with generating text-step-{n} where n is the multiplier step.
The Plan:
- Plugin File:
typographyScale.js
- Logic:
- Config:
base (1rem), ratio (1.25), range ([-2, 8]).
- Loop through range.
- Calculate
base * Math.pow(ratio, i).
- Return object
{ '-2': '0.64rem', '-1': '0.8rem', '0': '1rem', '1': '1.25rem', ... }.
- Tailwind Integration: Use
matchUtilities.
- Presets: Add a helper for common ratios (Minor Third, Major Third, Golden Ratio).
Let's refine the Line Height part. A typography scale plugin is much better if it handles line-height.
I will configure it so the value returned is [fontSize, { lineHeight: calculatedLineHeight }].
How to calculate calculatedLineHeight?
Common method: 1 + (1 / ratio). Or just a fixed map based on size?
Let's stick to a simpler method: Accept a lineHeight option in the config (e.g., a unitless number or 'auto').
Actually, let's just keep the generated utility simple (just ) but allow the user to pass an array if they want in the config, or just let the plugin calculate the size and the user uses classes.
The plugin will generate . I will add a section on how to add Line Height if desired.
This plugin generates utility classes (e.g., text-step-0, text-step-1) based on a mathematical Modular Scale. It supports custom bases, ratios, and automatic unit conversion (rem/px).
1. The Plugin Code (typographyScale.js)
Create a file named typographyScale.js (or add this to your tailwind.config.js directly).
const plugin = require('tailwindcss/plugin');
const _ = require('lodash');
module.exports = plugin(
function ({ matchUtilities, theme, addBase }) {
const config = theme('typographyScale', {});
// 1. Destructure configuration with defaults
const {
base = 1, // Base size in rems (e.g., 1)
ratio = 1.25, // Multiplier (Major Third)
range = [-2, 8], // [Start, End] steps
unit = 'rem', // 'rem' or 'px'
prefix = 'step', // Class prefix: text-step-0
lineHeights = {}, // Optional: specific line-heights per step
} = config;
const [start, end] = range;
// 2. Helper to calculate the step value
const calculateSize = (step) => {
// Formula: Base * (Ratio ^ Step)
let size = base * Math.pow(ratio, step);
// Handle Unit Conversion
// If base is assumed to be rems (1 = 16px), and we want px output:
if (unit === 'px') {
size = size * 16;
}
// Round to 3 decimal places for clean CSS
return parseFloat(size.toFixed(3));
};
// 3. Generate the values object { 0: '1rem', 1: '1.25rem', ... }
const scaleValues = {};
for (let i = start; i <= end; i++) {
const size = calculateSize(i);
const val = unit === 'px' ? `${size}px` : `${size}rem`;
// We map the integer step to the calculated CSS value
scaleValues[i] = val;
}
// 4. Register Utilities
// This creates classes like .text-step-2 { font-size: 1.563rem; }
matchUtilities(
{
[`text-${prefix}`]: (value, { modifier }) => {
// Allow modifier to handle line-height if passed in generic utility creation,
// but primarily we rely on the config 'lineHeights' map or separate leading utils.
return {
'font-size': value,
// Optional: Auto-attach line-height if defined in config
...(lineHeights[modifier] && { 'line-height': lineHeights[modifier] })
};
},
},
{
values: scaleValues,
// This allows matching the input modifier to the key (the step integer)
modifiers: scaleValues,
}
);
// 5. (Optional) Add CSS Variables to :root for use in JS or generic CSS
if (config.cssVariables) {
const cssVars = {};
for (let i = start; i <= end; i++) {
cssVars[`--font-${prefix}-${i}`] = scaleValues[i];
}
addBase({
':root': cssVars
});
}
},
{
theme: {
typographyScale: {
// Default configuration (can be overridden in tailwind.config.js)
base: 1,
ratio: 1.25, // Major Third
range: [-2, 8],
unit: 'rem',
prefix: 'step',
lineHeights: {},
cssVariables: true,
},
},
}
);
2. Configuration (tailwind.config.js)
Here is how you register and configure the plugin in your Tailwind setup.
// tailwind.config.js
const typographyScalePlugin = require('./typographyScale'); // Path to your file
module.exports = {
content: ['./src/**/*.{html,js}'],
theme: {
extend: {
// You can override the defaults here if you don't want to use the plugin defaults
typographyScale: {
base: 1, // 1rem (16px)
ratio: 1.333, // Perfect Fourth (Change to 1.5 for Major Second, etc.)
range: [-1, 10], // Generate steps -1 through 10
unit: 'rem', // Output unit
prefix: 'scale', // Result: text-scale-0, text-scale-1
cssVariables: true, // Generate :root variables
},
},
},
plugins: [
typographyScalePlugin,
// ... other plugins
],
};
3. Usage in HTML
The plugin generates text-{prefix}-{step} classes. The step corresponds to the exponent in the scale calculation (Size=Base×RatioStep).
- Step 0 is your base size.
- Positive steps get larger.
- Negative steps get smaller.
<div class="p-8 font-sans">
<!-- Base Size (Step 0): 1rem / 16px -->
<p class="text-scale-0">
This is the base text (Step 0).
</p>
<!-- Going Up (Step 1): Base * 1.333 -->
<h3 class="text-scale-1 mt-4">
This is Step 1
</h3>
<!-- Going Up Higher (Step 4): Base * 1.333^4 ≈ 3.16rem -->
<h1 class="text-scale-4 mt-4 font-bold">
This is Step 4
</h1>
<!-- Going Down (Step -1): Base / 1.333 -->
<small class="text-scale--1 text-gray-500 mt-4 block">
This is small text (Step -1)
</small>
</div>
4. Key Features & Logic
The Math
The plugin uses the modular scale formula:
Sn=B×Rn
Where B is the base, is the ratio, and is the step index.
Ratios Reference
When configuring ratio, you can use floats or math. Common web design ratios include:
- Minor Second:
1.067
- Major Second:
1.125
- Minor Third:
1.2
- Major Third:
1.25 (Default)
- Perfect Fourth:
1.333
- Golden Ratio:
1.618
CSS Variables
Because the plugin configuration sets cssVariables: true, it will automatically inject variables into your :root. This allows you to use these values in arbitrary values or custom CSS:
/* Generated CSS */
:root {
--font-scale-0: 1rem;
--font-scale-1: 1.333rem;
--font-scale-2: 1.777rem;
/* ... */
}
.my-custom-class {
font-size: var(--font-scale-5);
}