Skip to content

Tailwind CSS - 行高

行高(line height),在排版(typography)中常被称为“行距”(leading),控制着文本行之间的垂直距离。适当的行高对于可读性和创建视觉吸引力的设计至关重要。Tailwind 的 leading-* 工具类使其管理变得简单。

Tailwind 提供了两种行高工具类:相对行高和固定行高。在大多数情况下,建议使用相对行高,因为它们会随着元素的 font-size 成比例缩放。

这些类将一个无单位的乘数应用于当前的字体大小。这是最灵活和健壮的方法。

类名CSS 属性描述
leading-noneline-height: 1;无额外空间,行距紧密。
leading-tightline-height: 1.25;略微压缩的行距。
leading-snugline-height: 1.375;舒适但紧凑的行距。
leading-normalline-height: 1.5;大多数文本的良好默认值。
leading-relaxedline-height: 1.625;更宽敞,非常适合长篇文章。
leading-looseline-height: 2;非常开放,常用于风格效果。

这些类为行高应用一个特定的 rem 值。当你需要将文本对齐到固定网格时它们很有用,但不如相对单位灵活。

类名CSS 属性
leading-3line-height: .75rem; /* 12px */
leading-4line-height: 1rem; /* 16px */
leading-5line-height: 1.25rem; /* 20px */
leading-6line-height: 1.5rem; /* 24px */
……(以此类推)

此示例并排展示了不同的相对 leading 值,使其易于观察它们对可读性的影响。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tailwind Line Height Example</title>
<link href="./dist/output.css" rel="stylesheet">
</head>
<body class="bg-slate-50 p-8 font-sans">
<div class="max-w-2xl mx-auto">
<h1 class="text-3xl font-bold mb-6 text-slate-900">The Art of Readability</h1>
<div class="space-y-8">
<div>
<h3 class="font-semibold text-lg">leading-tight (1.25)</h3>
<p class="leading-tight text-slate-700 bg-slate-200 p-2 rounded">
Typography is the art and technique of arranging type to make written language legible, readable, and appealing when displayed. The arrangement of type involves selecting typefaces, point sizes, and line heights.
</p>
</div>
<div>
<h3 class="font-semibold text-lg">leading-normal (1.5)</h3>
<p class="leading-normal text-slate-700 bg-slate-200 p-2 rounded">
Typography is the art and technique of arranging type to make written language legible, readable, and appealing when displayed. The arrangement of type involves selecting typefaces, point sizes, and line heights.
</p>
</div>
<div>
<h3 class="font-semibold text-lg">leading-relaxed (1.625)</h3>
<p class="leading-relaxed text-slate-700 bg-slate-200 p-2 rounded">
Typography is the art and technique of arranging type to make written language legible, readable, and appealing when displayed. The arrangement of type involves selecting typefaces, point sizes, and line heights.
</p>
</div>
</div>
</div>
</body>
</html>
  • 最佳实践:对于像博客文章或文档这样的长篇内容,使用 leading-relaxed 或 leading-loose。额外的空间可以减少眼睛疲劳并提高理解力。
  • 对于标题:标题通常在行高更紧密时看起来更好,例如 leading-tight 或 leading-snug,特别是多行标题。
  • 自定义:你可以通过在 tailwind.config.js 文件中扩展 lineHeight 键,轻松地为你的项目添加自己的行高值。
  • tailwind.config.js
    module.exports = {
    theme: {
    extend: {
    lineHeight: {
    'extra-loose': '2.5',
    '12': '3rem',
    }
    }
    }
    }