Tailwind CSS - 字体粗细
Tailwind CSS:字体粗细
Section titled “Tailwind CSS:字体粗细”字体粗细工具类(Font weight utilities)用于控制文本的粗细或加粗程度。正确使用字体粗细对于创建文本层级结构、突出关键信息以及提升界面的整体可读性至关重要。
字体粗细类名参考
Section titled “字体粗细类名参考”Tailwind 提供了从 thin (100) 到 black (900) 的完整数字型字体粗细值范围。
| Class | CSS Property (font-weight) |
|---|---|
font-thin | 100 |
font-extralight | 200 |
font-light | 300 |
font-normal | 400 |
font-medium | 500 |
font-semibold | 600 |
font-bold | 700 |
font-extrabold | 800 |
font-black | 900 |
让我们创建一个文本块来展示不同的字体粗细。请注意,要使字体以特定的粗细渲染,浏览器必须加载该粗细的字体文件。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.tailwindcss.com"></script> <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@100..900&display=swap" rel="stylesheet"> <title>Font Weight Example</title> <style> body { font-family: 'Inter', sans-serif; } </style></head><body class="bg-white p-8 text-slate-700"> <div class="max-w-2xl mx-auto"> <h1 class="text-3xl font-extrabold text-slate-900 mb-2">Typographic Hierarchy</h1> <p class="text-lg font-light text-slate-500 mb-6">Using font weights to guide the reader's eye.</p>
<div class="space-y-4"> <p class="font-normal">This is the standard body text (`font-normal`), perfect for long-form reading.</p> <p class="font-medium">Medium weight (`font-medium`) can be used for subtitles or slightly emphasized text.</p> <p class="font-bold">For strong emphasis, `font-bold` is the standard choice. It's clear and effective.</p> <p class="font-black">The heaviest weight (`font-black`) is best used sparingly for impactful headlines.</p> </div> </div></body></html>响应式与状态变体
Section titled “响应式与状态变体”与大多数 Tailwind 工具类一样,字体粗细可以通过响应式前缀(如 sm:、md: 等)和状态前缀(如 hover:、focus: 等)有条件地应用。这对于交互式元素非常有用。
<!-- 这个链接在悬停时会加粗 --><a href="#" class="font-medium text-blue-600 hover:font-bold">Read more</a>
<!-- 这段文本在移动设备上是正常粗细,但在中等屏幕及以上会变为半粗体 --><p class="font-normal md:font-semibold">Important Announcement</p>字体平滑处理
Section titled “字体平滑处理”为了微调文本渲染效果,尤其是在 macOS 和 iOS 上,你可以使用字体平滑工具类。antialiased 使字体呈现更清晰、更细的观感,而 subpixel-antialiased 则提供更标准、略微厚重的观感。
<!-- 用于呈现清晰、现代的观感 --><body class="antialiased"> <!-- ... --></body>
<!-- 用于标准渲染 --><body class="subpixel-antialiased"> <!-- ... --></body>可访问性与最佳实践
Section titled “可访问性与最佳实践”- 避免正文使用极细字体: 像
font-thin和font-extralight这样的粗细值可能非常难以阅读,特别是对于视力障碍用户。将它们保留用于大型装饰性文本或标题。 - 确保字体可用性: 如果你使用了
font-bold,但用户的浏览器尚未加载该字体的粗体版本,它可能会尝试创建一个“伪粗体”版本,效果通常很差。始终确保你通过@font-face或像 Google Fonts 这样的服务加载了你打算使用的所有字体粗细。 - 层级结构是关键: 使用有限且一致的字体粗细组合来创建清晰的视觉层级结构。例如:标题使用
font-bold,副标题使用font-semibold,正文使用font-normal。