Skip to content

Tailwind CSS - 数字字体变体

Tailwind CSS 包含用于控制 OpenType 字体高级排版功能的实用工具类,例如数字、分数和序数的显示方式。这些类使您能够创建更精致、更专业的数字文本。

重要提示: 这些实用工具类仅在您使用的字体支持特定的 OpenType 功能时才会产生可见效果。许多标准系统字体支持有限。为获得最佳效果,请使用现代的、功能丰富的字体,如 Inter、Roboto 或 Fira Sans,这些字体通常可从 Google Fonts 等服务获取。

以下是可用的实用工具类及其主要用例。

ClassPropertiesBest For
normal-numsfont-variant-numeric: normal;重置所有特殊的数字样式。
ordinalfont-variant-numeric: ordinal;为序数词(如 1st, 2nd, 3rd)设置样式。
slashed-zerofont-variant-numeric: slashed-zero;在代码或 ID 中区分数字 0 和字母 O。
lining-numsfont-variant-numeric: lining-nums;将数字与大写字母的高度对齐。
oldstyle-numsfont-variant-numeric: oldstyle-nums;高度不一,能与正文文本融合的数字。
proportional-numsfont-variant-numeric: proportional-nums;具有可变宽度,在散文中阅读更佳的数字。
tabular-numsfont-variant-numeric: tabular-nums;在表格或财务数据中垂直对齐数字。
diagonal-fractionsfont-variant-numeric: diagonal-fractions;使用斜杠(如 1/2)样式化分数。
stacked-fractionsfont-variant-numeric: stacked-fractions;创建堆叠分数,常见于食谱中(例如 ½)。

此示例使用来自 Google Fonts 的 ‘Inter’ 字体,演示了不同字体数字变体类别的效果。请注意 tabular-nums 如何对齐 ‘Price’ 列中的数字,以及 slashed-zero 如何使 ‘Product ID’ 更清晰。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tailwind Font Variant Numeric</title>
<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;700&display=swap" rel="stylesheet">
<script src="https://cdn.tailwindcss.com"></script>
<style>
body {
font-family: 'Inter', sans-serif;
}
</style>
</head>
<body class="bg-gray-100 p-8">
<div class="max-w-2xl mx-auto bg-white p-6 rounded-lg shadow-md">
<h1 class="text-2xl font-bold mb-4">Product Inventory</h1>
<p class="mb-4 ordinal">
This is the **第 1** shipment of the month. The **第 2** will arrive on the **第 3**.
</p>
<table class="w-full text-left">
<thead>
<tr class="border-b">
<th class="p-2">Product ID</th>
<th class="p-2">Stock</th>
<th class="p-2 text-right">Price</th>
</tr>
</thead>
<tbody>
<tr class="border-b">
<td class="p-2 font-mono slashed-zero">PROD-A01B02</td>
<td class="p-2 tabular-nums">1,024</td>
<td class="p-2 text-right tabular-nums">$1,099.50</td>
</tr>
<tr class="border-b">
<td class="p-2 font-mono slashed-zero">PROD-C34O56</td>
<td class="p-2 tabular-nums">8</td>
<td class="p-2 text-right tabular-nums">$45.00</td>
</tr>
<tr>
<td class="p-2 font-mono slashed-zero">PROD-X98B00</td>
<td class="p-2 tabular-nums">15,000</td>
<td class="p-2 text-right tabular-nums">$120.75</td>
</tr>
</tbody>
</table>
<div class="mt-6">
<h2 class="font-bold">Recipe Fractions:</h2>
<p>Default: 1/2 cup flour, 3/4 tsp salt.</p>
<p class="diagonal-fractions">Diagonal: 1/2 cup flour, 3/4 tsp salt.</p>
<p class="stacked-fractions">Stacked: 1/2 cup flour, 3/4 tsp salt.</p>
</div>
</div>
</body>
</html>