text-wrap
Baseline 2024 *
新推出
text-wrap CSS 简写属性控制元素内文本的换行方式。不同的值提供:
- 排版改进,例如断裂标题之间更平衡的行长
- 一种完全关闭文本换行的方法。
试一试
text-wrap: wrap;
text-wrap: nowrap;
text-wrap: balance;
text-wrap: pretty;
text-wrap: stable;
<section class="default-example" id="default-example">
<div class="whole-content-wrapper">
<p>Edit the text in the box:</p>
<div class="transition-all" id="example-element">
<p contenteditable="">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatem aut
cum eum id quos est.
</p>
</div>
</div>
</section>
.whole-content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
#example-element {
border: 1px solid #c5c5c5;
width: 250px;
}
构成属性
此属性是以下 CSS 属性的简写:
语法
/* Keyword values */
text-wrap: wrap;
text-wrap: nowrap;
text-wrap: balance;
text-wrap: pretty;
text-wrap: stable;
/* Global values */
text-wrap: inherit;
text-wrap: initial;
text-wrap: revert;
text-wrap: revert-layer;
text-wrap: unset;
text-wrap 属性指定为从以下值列表中选择的单个关键字。
值
wrap-
文本在适当的字符处(例如,在像英语这种使用空格分隔符的语言中是空格)换行,以最大限度地减少溢出。这是默认值。
nowrap-
文本不跨行换行。它会溢出其包含元素,而不是断到新行。
balance-
文本以最佳方式平衡每行字符数的方式换行,从而提高布局质量和可读性。由于计算字符并在多行中平衡它们计算成本高昂,因此此值仅支持跨越有限行数(Chromium 为六行或更少,Firefox 为十行或更少)的文本块。
pretty-
结果与
wrap相同,不同之处在于用户代理将使用较慢的算法,该算法倾向于更好的布局而不是速度。这适用于正文文本,其中良好的排版优于性能(例如,当应将孤行数保持在最低限度时)。 stable-
结果与
wrap相同,不同之处在于当用户编辑内容时,他们正在编辑的行之前的行保持静态,而不是整个文本块重新换行。
描述
文本可以在内容块(例如段落 (<p>) 或标题 (<h1>–<h6>))内跨行流动的方式有两种。它们是用户控制的强制换行和浏览器控制的软换行。text-wrap 属性可用于提示浏览器如何控制软换行。
您为 text-wrap 选择的值取决于您预计要设置样式的文本行数、文本是否可 contenteditable,以及您是否需要优先考虑外观或性能。
当样式化内容仅限于少量行时,例如标题、说明和引用块,可以添加 text-wrap: balance 以平衡每行字符数,从而提高布局质量和可读性。由于浏览器限制了受此属性影响的行数,因此此值对性能的影响可以忽略不计。
对于较长的文本段落,可以使用 text-wrap: pretty。请注意,pretty 对性能有负面影响,因此应仅在布局比速度更重要时用于较长的文本块。
当用于contenteditable 内容时,stable 值可改善用户体验。此值确保当用户编辑文本时,正在编辑区域中的前几行保持稳定。
正式定义
| 初始值 | wrap |
|---|---|
| 应用于 | 文本和块容器 |
| 继承性 | 是 |
| 百分比 | 作为简写中的每个属性
|
| 计算值 | 作为简写中的每个属性
|
| 动画类型 | 作为简写中的每个属性
|
正式语法
text-wrap =
<'text-wrap-mode'> ||
<'text-wrap-style'>
<text-wrap-mode> =
wrap |
nowrap
<text-wrap-style> =
auto |
balance |
stable |
pretty |
avoid-orphans
示例
基本文本换行值比较
HTML
<h2 class="wrap" contenteditable="true">
The default behavior; the text in the heading wraps "normally"
</h2>
<h2 class="nowrap" contenteditable="true">
In this case the text in the heading doesn't wrap, and overflows the container
</h2>
<h2 class="balance" contenteditable="true">
In this case the text in the heading is nicely balanced across lines
</h2>
CSS
.wrap {
text-wrap: wrap;
}
.nowrap {
text-wrap: nowrap;
}
.balance {
text-wrap: balance;
}
h2 {
font-size: 2rem;
font-family: sans-serif;
}
结果
示例中的文本是可编辑的。更改文本,添加长单词,以查看不同行和单词长度如何影响换行。
规范
| 规范 |
|---|
| CSS 文本模块第 4 级 # text-wrap-shorthand |
浏览器兼容性
加载中…
另见
white-spacewhite-space-collapse- CSS 文本模块
- developer.chrome.com 上的 CSS
text-wrap: balance(2023) - developer.chrome.com 上的 CSS
text-wrap: pretty(2023) - Kelly Choyce-Dwan 撰写的平衡日语和韩语排版 (2025)