Sub topic 14
Extending the spacing and type scale in your theme
This chapter assumes you can read Tailwind class lists and know the default spacing scale (p-4, gap-6) and the font-size utilities (text-lg). It also assumes you know whether your project uses Tailwind v3 (a tailwind.config.js file) or v4 (CSS-first configuration).
When to change the theme
Arbitrary values such as w-[320px] work for a single use. If the same value shows up in several places, give it a name in the theme. A name documents intent (p-gutter says more than p-[1.5rem]) and lets you change the value in one place.
Extending spacing in v3
In v3, add keys under theme.extend.spacing. Extending keeps the default scale and adds your names beside it.
// tailwind.config.js (Tailwind v3)
module.exports = {
theme: {
extend: {
spacing: {
gutter: '1.5rem',
},
},
},
}This generates p-gutter, mt-gutter, gap-gutter, and also w-gutter and h-gutter, because the spacing scale feeds padding, margin, gap, width, and height.
Extending spacing in v4
In v4, you declare a CSS variable in an @theme block. The --spacing-* namespace works the same way.
/* app.css (Tailwind v4) */
@import "tailwindcss";
@theme {
--spacing-gutter: 1.5rem;
}Adding a font size with its line height
A font size usually needs a matching line height. In v3, pass an array of the size and an options object.
// tailwind.config.js (Tailwind v3)
module.exports = {
theme: {
extend: {
fontSize: {
tiny: ['0.75rem', { lineHeight: '1rem' }],
},
},
},
}In v4, the line height goes in a second variable whose name adds --line-height to the size variable.
/* app.css (Tailwind v4) */
@import "tailwindcss";
@theme {
--text-tiny: 0.75rem;
--text-tiny--line-height: 1rem;
}Both versions give you text-tiny, which sets the size and line height together, like the built-in text-sm.
<p class="p-gutter text-tiny">Small print with a named gutter.</p>Common errors
- Replacing instead of extending (v3). Putting
spacingdirectly underthemeremoves the default scale, sop-4stops working. Usetheme.extend.spacingunless you want to replace the scale. - Editing the wrong file. A v4 project ignores
tailwind.config.jsunless you load it explicitly. Check which system your project uses before adding values. - Forgetting the line height. A new font size without a line height inherits whatever the surrounding text has, which often looks cramped.
- Wrong key names. The utility name comes from the key.
--spacing-guttergivesgutter, not--spacing-gutter-size. - Over-extending. A theme with dozens of near-duplicate values defeats the purpose of a scale. Add a value only when it repeats.
Exercise
Exercise
Your team wants p-section to equal 5rem in a Tailwind v4 project, and a text-caption size of 0.8125rem with a 1.25rem line height. What goes in app.css?
Show answer
Inside an @theme block, after @import "tailwindcss";, declare --spacing-section: 5rem;, --text-caption: 0.8125rem;, and --text-caption--line-height: 1.25rem;. This generates p-section and text-caption.