Designing Type Scales
I'm currently focused on defining the core functionality of this Tailwind plugin. It needs to generate custom typography scales. I'm thinking about how users will input their desired parameters to fine-tune these scales within their designs. Flexibility and user-friendliness are key priorities.
Planning the Implementation
I've been mapping out the plugin's structure. It should let users define font sizes and line heights via a modular scale. The plan involves generating Tailwind utility classes like text-scale-1 and text-scale-2. I'm focusing on the base size, ratio, and step count now.
Streamlining the Approach
I'm now prioritizing simplicity for the initial version. Static scale generation based on configuration will be the Minimum Viable Product. Fluid typography, while appealing, might unnecessarily complicate the core logic. The goal is to output classes like .text-scale-base, .text-scale-lg, etc., potentially replacing the standard Tailwind classes. I'm focusing on a clean structure for the config object, the size calculation, unit conversion to REM for accessibility, and considering how to manage line heights.
Iterating on Implementation
I'm diving into the actual code now. I'm focusing on a clean loop to calculate font sizes and an optional, but recommended, line-height. Naming is crucial, so I've considered Tailwind's convention but decided on a configurable mathematical approach with prefixes like text-type-1. For the first draft, I'm setting up a configurable base size and ratio. Then, I'll extend to allow for more customization.
Implementing Theme Extension
I'm now focusing on reading from theme('typographyScale'). It's clear extending the theme is the preferred Tailwind method for typography. However, I need this plugin to generate scales. So, the best approach is to make a plugin that allows defining a math-based scale and outputs utilities like .text-scale-1. I'll focus on injecting these utilities while making them configurable, including rem calculation. I'm finalizing the plugin code structure, defining the import statements, helper functions and main functions.
Polishing the Details
I'm now integrating line height adjustment into the utility generation, ensuring visual harmony across sizes. Smaller text gets a more open line height, and vice versa. I'm finalizing the logic for lineHeight, iterating on the overall example, including plugin code, config setup, and usage examples, to provide a complete guide. I'm also reviewing against the TW constraints. I'm writing the response document, including introduction, code explanations, configuration steps, and usage examples.
Fine-Tuning the Naming
I've revised the naming scheme for the text scale classes. They'll be text-level-{n} for consistent and generic usage. I'm focusing on clean code now and implementing a helper for rem rounding to improve CSS clarity. I'm building out example classes for users to follow, and also considering how TypeScript can be used to make these plugins more accessible. I'm focused on the generated classes, including their names.
This is a comprehensive guide to creating a Tailwind CSS plugin that generates a Modular Typography Scale.
This plugin will allow you to define a base size and a ratio (like the Golden Ratio or Major Third), and it will automatically generate the utility classes (calculated in rem) for you.
Prerequisite
Ensure you have Tailwind CSS installed.
1. The Plugin Code (typography-scale-plugin.js)
Create a file named typography-scale-plugin.js. We will use the plugin function from Tailwind.
const plugin = require('tailwindcss/plugin');
/**
* Helper to round numbers to specific decimal places
*/
const round = (num, decimals = 4) =>
Number(Math.round(num + "e" + decimals) + "e-" + decimals);
module.exports = plugin.withOptions(
// Default Options
(options = {}) => {
return ({ addUtilities, theme, e }) => {
const config = theme('typographyScale') || {};
// Merge user config with defaults
const settings = {
prefix: options.prefix || 'type', // Class prefix (e.g., text-type-1)
baseSize: config.base || 16, // Base size in pixels (usually 1rem)
ratio: config.ratio || 1.25, // Major Third by default
stepsDown: config.stepsDown || 2, // How many sizes smaller than base
stepsUp: config.stepsUp || 6, // How many sizes larger than base
decimals: config.decimals || 3, // Formatting precision
...options,
};
const utilities = {};
const { baseSize, ratio, stepsDown, stepsUp, prefix, decimals } = settings;
// Generate the range of numbers (e.g., -2, -1, 0, 1, 2...)
const range = [];
for (let i = -stepsDown; i <= stepsUp; i++) {
range.push(i);
}
range.forEach((step) => {
// Formula: size = base * (ratio ^ step)
const sizePx = baseSize * Math.pow(ratio, step);
const sizeRem = round(sizePx / 16, decimals); // Assuming root is 16px
// Calculate Line Height (Optional logic: Tighter line height for larger text)
// Logic: Start at 1.5 and decrease slightly as text gets bigger
let lineHeight = 1.5;
if (step > 0) lineHeight = round(1.5 - (step * 0.05), 2);
if (lineHeight < 1.1) lineHeight = 1.1; // Cap minimum line height
// Generate the class name.
// e.g., .text-type-base, .text-type-1, .text-type--1
let stepName = step === 0 ? 'base' : step.toString();
// Handle negative numbers for class names (e.g., 'text-type--1')
// Tailwind automatically handles negative values nicely usually,
// but we construct the string explicitly here.
const className = `.text-${prefix}-${stepName}`;
utilities[className] = {
'font-size': `${sizeRem}rem`,
'line-height': `${lineHeight}`,
};
});
addUtilities(utilities, ['responsive']);
};
}
);
2. Configure tailwind.config.js
Now you need to import the plugin and configure your scale settings.
// tailwind.config.js
const typographyScale = require('./typography-scale-plugin');
module.exports = {
content: ["./src/**/*.{html,js}"],
theme: {
extend: {
// Define your scale settings here
typographyScale: {
base: 16, // 1rem
ratio: 1.333, // Perfect Fourth
stepsDown: 2, // Generates -1, -2
stepsUp: 8, // Generates 1 through 8
},
},
},
plugins: [
// Initialize the plugin
typographyScale({
prefix: 'scale', // Resulting classes: text-scale-1, text-scale-base
}),
],
};
3. How to Use It
Once configured, the plugin generates utility classes based on the math. Since we set the prefix to scale in the config above, the classes will look like this:
- Base:
text-scale-base (The base 1rem)
- Larger:
text-scale-1, text-scale-2 ... text-scale-8
- Smaller:
text-scale--1, text-scale--2
HTML Example:
<div class="p-10">
<span class="text-scale--2 text-gray-500">Caption / Small text (-2)</span>
<h1 class="text-scale-5 font-bold">
Major Heading (Level 5)
</h1>
<h2 class="text-scale-3 font-semibold">
Subheading (Level 3)
</h2>
<p class="text-scale-base mt-4 max-w-prose">
This is your body text sitting at the calculated base size.
The plugin automatically calculated the rem values based on your ratio.
</p>
<!-- Responsive works too -->
<p class="text-scale-1 md:text-scale-2 lg:text-scale-3 text-blue-600 mt-4">
This text grows with the screen size!
</p>
</div>
4. Advanced: Common Ratios Reference
When configuring the ratio in your tailwind.config.js, you can use these standard typographic scale ratios:
- Minor Second:
1.067
- Major Second:
1.125
- Minor Third:
1.200
- Major Third:
1.250 (Safe default)
- Perfect Fourth:
1.333
- Augmented Fourth:
1.414
- Perfect Fifth:
1.500
- Golden Ratio:
1.618
5. Customizing Line Height Logic
In the plugin code provided above, I included a simple dynamic line-height logic:
// Tighter line heights for larger headings
if (step > 0) lineHeight = round(1.5 - (step * 0.05), 2);
If you prefer static line heights regardless of size, modify that section in typography-scale-plugin.js:
utilities[className] = {
'font-size': `${sizeRem}rem`,
'line-height': '1.5', // Fixed line height
};
Or, if you want standard Tailwind behavior (where you manually add leading-tight, etc.), simply remove the 'line-height' key from the utilities object entirely.