Tailwind CSS Academy · 课时

自定义字体系列

在配置中定义 fontFamily,集成 Google Fonts 或本地字体,并使用 font-* 实用程序 class 应用它们。

第 2 / 4 课13 个步骤

自定义字体系列 是 CoddyKit 上的免费 Tailwind CSS Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Tailwind CSS Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Tailwind CSS Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Tailwind's Default Font Stacks

Tailwind provides three default font family utilities: font-sans, font-serif, and font-mono. Each maps to a carefully chosen system font stack that looks good across all operating systems without requiring any font downloads. For most projects, you will want to replace or augment these with a branded web font that gives your project a distinctive typographic identity.

/* Tailwind's built-in font stacks */
font-sans  → ui-sans-serif, system-ui, -apple-system, ...
font-serif → ui-serif, Georgia, Cambria, ...
font-mono  → ui-monospace, SFMono-Regular, Menlo, ...

<!-- Using them -->
<p class="font-sans">System sans-serif text</p>
<p class="font-serif">Elegant serif text</p>
<pre class="font-mono">code example</pre>

Choosing a Google Font

Google Fonts is the most common source of free web fonts. Browse fonts.google.com and select a font that fits your brand. Popular choices for UI projects include Inter for clean modern interfaces, Geist for technical products, Playfair Display for editorial elegance, and JetBrains Mono for code editors. Choose the weights you actually use (regular 400 and semibold 600 cover most cases).

<!-- Add to your HTML <head> to load from Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">

<!-- Or for Playfair Display -->
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&display=swap" rel="stylesheet">

Registering Fonts in Tailwind Config

After loading the font via a <link> tag or CSS @import, register it in tailwind.config.js under theme.extend.fontFamily. Provide the font name exactly as it appears in Google Fonts (with spaces if applicable) as the first item in a stack array. Always include fallback fonts — system fonts as backup in case the web font fails to load.

// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      fontFamily: {
        sans: ['Inter', 'ui-sans-serif', 'system-ui', 'sans-serif'],
        display: ['Playfair Display', 'Georgia', 'serif'],
        mono: ['JetBrains Mono', 'ui-monospace', 'SFMono-Regular', 'monospace'],
      },
    },
  },
};

Applying Font Families in HTML

Once registered, use the font-{key} utility class to apply the font. If you extended sans, then font-sans now resolves to your chosen font. If you added a new key like display, the utility class is font-display. Apply the font family at the highest ancestor level to inherit it everywhere, then override specific sections as needed.

<body class="font-sans">
  <!-- All text inherits Inter font -->

  <h1 class="font-display text-5xl font-bold">
    Playfair Display Heading
  </h1>

  <p class="font-sans text-gray-600">
    Regular body text in Inter
  </p>

  <pre class="font-mono text-sm bg-gray-100 p-4 rounded">
    code in JetBrains Mono
  </pre>
</body>

Replacing the Default Font Family

To make your chosen font the default everywhere without adding font-sans to every element, override theme.fontFamily.sans (outside extend) to replace the default stack entirely. Then apply font-sans once on your body element, and all text that inherits from body will use your custom font without any additional class names.

// tailwind.config.js — Override default sans (replaces the default)
module.exports = {
  theme: {
    fontFamily: {
      sans: ['Inter', 'ui-sans-serif', 'system-ui', 'sans-serif'],
      // serif and mono keep defaults unless also overridden
    },
  },
};

<!-- Now font-sans = Inter everywhere -->
<body class="font-sans">
  <p>This text automatically uses Inter</p>
</body>

Loading Fonts with Next.js Font Optimization

In Next.js projects, use the next/font module instead of Google Fonts CDN links. It downloads fonts at build time, serves them from your own domain, eliminates external requests, and prevents layout shift with automatic font size adjustments. Generate the CSS variable name and pass it to your Tailwind config using that variable, creating a tight integration between Next.js font optimization and Tailwind.

// app/layout.tsx
import { Inter } from 'next/font/google';

const inter = Inter({
  subsets: ['latin'],
  variable: '--font-inter',
});

export default function Layout({ children }) {
  return (
    <html lang="en" className={inter.variable}>
      <body className="font-sans">{children}</body>
    </html>
  );
}

// tailwind.config.js
theme: {
  extend: {
    fontFamily: {
      sans: ['var(--font-inter)', 'ui-sans-serif', 'system-ui'],
    },
  },
}

Using Local Font Files

When using purchased or custom fonts, host them locally and define them with a CSS @font-face rule. Place font files in your public directory and reference them with absolute paths. Use font-display: swap to show fallback fonts immediately while the custom font loads, preventing invisible text during load. Then register the font family in your Tailwind config as usual.

/* In your global CSS */
@font-face {
  font-family: 'BrandFont';
  src: url('/fonts/BrandFont-Regular.woff2') format('woff2'),
       url('/fonts/BrandFont-Regular.woff') format('woff');
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}

/* tailwind.config.js */
theme: {
  extend: {
    fontFamily: {
      brand: ['BrandFont', 'sans-serif'],
    },
  },
}

Font Weight Utilities

After setting the font family, control weight with Tailwind's font-{weight} utilities. Common weights include font-normal (400), font-medium (500), font-semibold (600), and font-bold (700). Make sure you load the specific weights from Google Fonts that you intend to use — requesting a weight that is not loaded causes the browser to synthesize it, resulting in poor-quality text.

<!-- Load weights 400, 600, 700 from Google -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">

<!-- Use them with Tailwind weight utilities -->
<p class="font-sans font-normal">Regular body text (400)</p>
<p class="font-sans font-semibold">Semibold text (600)</p>
<h1 class="font-sans font-bold">Bold heading (700)</h1>

Variable Fonts

Variable fonts contain all weights (and sometimes widths and italics) in a single file, reducing HTTP requests while supporting the full weight range. Load a variable font once and use any Tailwind font-weight utility without worrying about whether that specific weight was requested. Many modern Google Fonts now offer variable versions — look for the ital,wght@ axis syntax in the URL.

<!-- Variable font: loads once, supports all weights 100-900 -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap" rel="stylesheet">

<!-- Now ALL weight utilities work with Inter -->
<p class="font-thin">font-thin (100)</p>
<p class="font-normal">font-normal (400)</p>
<p class="font-bold">font-bold (700)</p>
<p class="font-black">font-black (900)</p>

Font Smoothing Utilities

Tailwind provides antialiased and subpixel-antialiased utilities that control how fonts are rendered on screen. Apply antialiased globally on your body to enable grayscale antialiasing, which makes modern web fonts look crisper and thinner on high-DPI displays. Most Tailwind projects add antialiased as a base style alongside the font family declaration.

<body class="font-sans antialiased text-gray-900">
  <!-- Text renders with smooth antialiasing across the page -->

  <h1 class="font-bold text-4xl tracking-tight">
    Crisp, antialiased heading
  </h1>
</body>

Testing Font Loading

Verify your custom fonts load correctly by opening Chrome DevTools, going to the Network tab, and filtering by Font. You should see your font files listed. In the Elements panel, select a text node and check the Computed tab — the font-family property should show your custom font name as the resolved font, not the fallback. Test at multiple viewport sizes and connection speeds to catch loading issues.

Quick Check

Test your understanding of custom font families in Tailwind CSS.

Lesson Recap

In this lesson you learned: register custom fonts in theme.extend.fontFamily as an array with fallback fonts, load Google Fonts via a CDN <link> tag or use next/font for optimized loading in Next.js, and apply antialiased globally for crisp font rendering. Next up we add custom spacing values to fill gaps in Tailwind's default scale.

免费开始

用 AI 导师学习 HTML — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
30
课程
120

常见问题解答

「自定义字体系列」课时是免费的吗?

是的 — 「自定义字体系列」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Tailwind CSS Academy 课程的其余内容,请升级到 CoddyKit PRO。 Tailwind CSS Academy 课程共包含 4 节课。

「自定义字体系列」这节课中我会学到什么?

在配置中定义 fontFamily,集成 Google Fonts 或本地字体,并使用 font-* 实用程序 class 应用它们。 你通过在浏览器中直接运行的动手代码来练习 Tailwind CSS Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Tailwind CSS Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Tailwind CSS Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「自定义字体系列」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Tailwind CSS Academy 课中编写并运行代码吗?

能。每节 Tailwind CSS Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 添加自定义颜色
  2. 自定义字体系列
  3. 自定义间距值
  4. 在 Tailwind 中使用 CSS 变量
← 返回 Tailwind CSS Academy