Skip to content

Tailwind CSS - 文本溢出

在现代 UI 设计中,处理可能超出其容器边界的动态文本是一个常见挑战。Tailwind 的文本溢出(Text Overflow)工具类提供了优雅的解决方案,可以剪裁、截断溢出文本或为其添加省略号(…)。

当文本不适合其容器时,这些工具类控制其显示方式。

类CSS 属性
truncateoverflow: hidden; text-overflow: ellipsis; white-space: nowrap;
text-ellipsistext-overflow: ellipsis;
text-cliptext-overflow: clip;
  • truncate:这是你首选的、一体化工具类。它强制文本单行显示(white-space: nowrap),隐藏任何溢出部分,并在末尾添加省略号(...)。
  • text-ellipsis:如果你想自行管理 overflow 和 white-space 属性但仍需要省略号效果,请使用此项。
  • text-clip:这只是在容器边缘剪切文本,不带任何视觉指示器(如省略号)。适用于某些设计美学。

让我们构建一个产品卡片,其中标题和描述的长度可能各不相同。我们将使用文本溢出工具类来保持整洁一致的布局。

<div class="font-sans antialiased bg-slate-100 flex justify-center items-center min-h-screen p-4">
<div class="w-full max-w-xs bg-white rounded-lg shadow-lg overflow-hidden">
<img class="w-full h-40 object-cover" src="https://source.unsplash.com/random/400x300?product" alt="Product Image">
<div class="p-4">
<h3 class="text-lg font-bold text-slate-800 truncate" title="An Extremely Long and Detailed Product Title That Will Surely Overflow">
An Extremely Long and Detailed Product Title That Will Surely Overflow
</h3>
<p class="mt-2 text-sm text-slate-600 text-clip overflow-hidden h-10">
This description uses text-clip. It just cuts off without an ellipsis, which can be a specific design choice. It will not show more content.
</p>
<div class="mt-4 flex justify-between items-center">
<span class="text-xl font-bold text-slate-900">$99.99</span>
<button class="px-4 py-2 bg-blue-600 text-white text-sm font-semibold rounded-md hover:bg-blue-700">Add to Cart</button>
</div>
</div>
</div>
</div>

一个常见需求是在特定行数后截断文本。虽然这默认不在 Tailwind 的核心功能中,但使用官方的 @tailwindcss/line-clamp 插件可以轻松实现。

# 1. 安装插件
npm install -D @tailwindcss/line-clamp
# 2. 将其添加到你的 tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
// ...
plugins: [
require('@tailwindcss/line-clamp'),
],
}

示例:使用 Line-Clamp 的卡片描述

Section titled “示例:使用 Line-Clamp 的卡片描述”

现在你可以使用 line-clamp-{n} 工具类在设定的行数后截断文本。

<div class="max-w-xs mx-auto my-8 bg-white rounded-lg shadow-lg p-4">
<h3 class="text-lg font-bold">Multi-line Truncation</h3>
<p class="mt-2 text-slate-600 line-clamp-3">
This is a long paragraph that is designed to demonstrate the line-clamp functionality.
It will span multiple lines, but thanks to the plugin, it will be elegantly truncated
with an ellipsis after the third line, ensuring the UI remains clean and tidy regardless
of the content length.
</p>
</div>
  • truncate 不工作? 最常见的原因是元素或其父元素没有定义宽度限制。truncate 需要知道边界才能计算溢出。请确保元素具有 w-*、max-w-* 工具类,或者位于限制其大小的 flex/grid 容器内。
  • text-ellipsis 或 text-clip 没有效果? 这些工具类仅在 overflow 设置为 hidden、scroll 或 auto 时才起作用。你通常需要同时添加 overflow-hidden 工具类。