Skip to content

Tailwind CSS - 空白

Tailwind 的 whitespace 工具类让您能够精确控制元素内空白区域(空格、制表符、换行符)和文本换行的处理方式。掌握这些类是构建健壮且可预测布局的关键。

专业提示: whitespace 工具类通常与 overflow 和 text-overflow 类(例如 truncate)结合使用,以优雅地管理长内容。

以下是用于控制文本换行和空白区域保留的主要类。

类名CSS 属性与行为
whitespace-normalwhite-space: normal; (默认) 文本正常换行。
whitespace-nowrapwhite-space: nowrap; 文本不会换行到下一行。
whitespace-prewhite-space: pre; 保留所有空白区域和换行符。文本仅在源代码中的换行处换行。
whitespace-pre-linewhite-space: pre-line; 折叠连续的空白区域但保留换行符。
whitespace-pre-wrapwhite-space: pre-wrap; 保留空白区域但允许文本换行。
whitespace-break-spaceswhite-space: break-spaces; 类似于 pre-wrap,但任何保留的空白序列都可以换行。

以下示例展示了 whitespace 工具类在现代 UI 中的常见用例。

UI 元素(如按钮或表格单元格)的常见模式是防止文本换行,并在文本过长时显示省略号 (…)。这通过结合 whitespace-nowrap、overflow-hidden 和 truncate 实现。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Whitespace Truncation Example</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-8">
<div class="max-w-xs mx-auto">
<button class="w-full bg-blue-500 text-white font-bold py-2 px-4 rounded overflow-hidden whitespace-nowrap text-ellipsis">
This is a very long text that will be truncated.
</button>
<!-- `truncate` 类是上述三个工具类的简写 -->
<button class="mt-4 w-full bg-green-500 text-white font-bold py-2 px-4 rounded truncate">
This is a very long text that will be truncated.
</button>
</div>
</body>
</html>

在显示代码时,您会希望保留与源代码中完全一致的缩进和换行。whitespace-pre-wrap 在这方面表现完美,因为它在保持格式的同时,仍允许容器具有响应性。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Whitespace Code Block Example</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 p-8">
<div class="max-w-2xl mx-auto">
<h2 class="text-xl font-semibold text-slate-800 mb-2">Code Example:</h2>
<pre class="bg-slate-800 text-white p-4 rounded-lg overflow-x-auto">
<code class="whitespace-pre-wrap font-mono text-sm">
function greet() {
// 此函数用于向用户问好。
console.log("Hello, World!");
}
</code>
</pre>
</div>
</body>
</html>

与大多数 Tailwind 工具类一样,whitespace 类可以根据不同断点有条件地应用。例如,您可能希望文本在小屏幕上换行,但在大屏幕上保持一行。

<!-- 文本在小屏幕上换行,但在中等及以上屏幕上不换行 -->
<p class="whitespace-normal md:whitespace-nowrap">
This text will wrap on mobile but will form a single line on desktop.
</p>
  • 意外的水平滚动: 对元素应用 whitespace-nowrap 可能会导致其容器水平溢出。如果不希望出现这种情况,请确保其父元素具有 overflow-hidden 或类似的约束。
  • truncate 未生效: truncate 工具类要求元素具有明确的宽度约束(例如 w-full、max-w-md,或位于 flex/grid 容器中)才能正常工作。