Skip to content

Tailwind CSS - 字体大小

使用 Tailwind CSS 实现响应式字体大小

Section titled “使用 Tailwind CSS 实现响应式字体大小”

Tailwind CSS 提供了一组 text-* 实用工具类来控制元素的字体大小。这些工具类是预定义排版比例的一部分,可确保您的应用程序在视觉上保持一致性。默认情况下,它们使用 rem 单位,这是无障碍性(accessibility)的最佳实践,因为它尊重用户的浏览器字体大小设置。

以下是 Tailwind 提供的默认字体大小实用工具比例。每个工具类都设置了 font-size 和一个合理的默认 line-height。

ClassCSS Properties (Font Size / Line Height)
text-xsfont-size: 0.75rem; (12px) / line-height: 1rem; (16px)
text-smfont-size: 0.875rem; (14px) / line-height: 1.25rem; (20px)
text-basefont-size: 1rem; (16px) / line-height: 1.5rem; (24px)
text-lgfont-size: 1.125rem; (18px) / line-height: 1.75rem; (28px)
text-xlfont-size: 1.25rem; (20px) / line-height: 1.75rem; (28px)
text-2xlfont-size: 1.5rem; (24px) / line-height: 2rem; (32px)
text-3xlfont-size: 1.875rem; (30px) / line-height: 2.25rem; (36px)
text-4xlfont-size: 2.25rem; (36px) / line-height: 2.5rem; (40px)
text-5xlfont-size: 3rem; (48px) / line-height: 1;
text-6xlfont-size: 3.75rem; (60px) / line-height: 1;
text-7xlfont-size: 4.5rem; (72px) / line-height: 1;
text-8xlfont-size: 6rem; (96px) / line-height: 1;
text-9xlfont-size: 8rem; (128px) / line-height: 1;

Tailwind 的一个关键特性是响应式设计。您可以通过使用 sm:, md:, lg: 和 xl: 等断点前缀,轻松地在不同屏幕尺寸下更改字体大小。

<!-- Starts at text-lg on small screens, becomes text-2xl on medium screens, and text-4xl on large screens -->
<h1 class="text-lg md:text-2xl lg:text-4xl">Responsive Heading</h1>

对于默认比例未涵盖的特定设计要求,您无需离开 HTML 即可使用任意值。这非常适合对排版进行微调。

<!-- Set a very specific font size -->
<p class="text-[15px]">This paragraph has a 15px font size.</p>
<!-- You can also define a custom line height -->
<p class="text-[15px]/[22px]">Font size of 15px with a line height of 22px.</p>

要强制执行项目特定的排版比例,您可以在 tailwind.config.js 文件中扩展默认字体大小。

tailwind.config.js
module.exports = {
theme: {
extend: {
fontSize: {
'2xs': '0.625rem', // 10px
'clamp': 'clamp(1rem, 5vw, 2.5rem)', // Fluid typography
},
},
},
}

此示例演示了如何应用不同的字体大小实用工具类来创建结构良好且响应式的文本块。

<!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>
<title>Responsive Typography</title>
</head>
<body class="font-sans p-4 md:p-8 bg-gray-50">
<article class="max-w-3xl mx-auto">
<h1 class="font-bold text-gray-900 text-3xl md:text-4xl lg:text-5xl mb-4">
The Art of Responsive Typography
</h1>
<p class="text-gray-500 text-base md:text-lg mb-6">
Published on October 26, 2023
</p>
<div class="prose prose-lg max-w-none text-gray-800">
<p class="text-base mb-4">
This is the body text, set to `text-base`. It provides a comfortable reading experience on all devices. For larger screens, we could increase this to `md:text-lg` for better readability.
</p>
<p class="text-sm text-gray-600">
This is a smaller caption or annotation, using `text-sm`. It's distinct from the main body text but still perfectly legible.
</p>
</div>
</article>
</body>
</html>