This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

* Some parts of this feature may have varying levels of support.

Learn more <div id="example-element"> But ere she from the church-door stepped She smiled and told us why: 'It was a wicked woman's curse,' Quoth she, 'and what care I?' She smiled, and smiled, and passed it off Ere from the door she stept— </section>
#example-element {
  width: 16rem;
#example-element p {
  border: 1px solid #c5c5c5;
  padding: 0.75rem;
  text-align: left;

这个属性指定了两件事:

  • 空白字符是否合并,以及如何合并。
  • 是否换行,以及如何换行。
  • 要使单词可以在其内部被截断,请使用 overflow-wrapword-breakhyphens 代替。

    css
    /* 单个关键字值 */
    white-space: normal;
    white-space: nowrap;
    white-space: pre;
    white-space: pre-wrap;
    white-space: pre-line;
    white-space: break-spaces;
    /* white-space-collapse 和 text-wrap 简写值 */
    white-space: collapse balance;
    white-space: preserve nowrap;
    /* 全局值 */
    white-space: inherit;
    white-space: initial;
    white-space: revert;
    white-space: revert-layer;
    white-space: unset;
        

    white-space 属性可以被指定为从下面的值列表中选择的单个关键字,或者是表示 white-space-collapsetext-wrap 属性的简写的两个值。

    normal

    连续的空白符会被合并。源码中的换行符会被当作空白符来处理。并根据填充行框盒子的需要来换行。

    nowrap

    normal 一样合并空白符,但阻止源码中的文本换行。

    连续的空白符会被保留。仅在遇到换行符或 <br> 元素时才会换行。

    pre-wrap

    连续的空白符会被保留。在遇到换行符或 <br> 元素时,或者根据填充行框盒子的需要换行。

    pre-line

    连续的空白符会被合并。在遇到换行符或 <br> 元素时,或者根据填充行框盒子的需要换行。

    break-spaces

    pre-wrap 的行为相同,除了:

  • 任何保留的空白序列总是占用空间,包括行末的。
  • 每个保留的空白字符后(包括空白字符之间)都可以被截断。
  • 这样保留的空间占用空间而不会挂起,从而影响盒子的固有尺寸(min-content 尺寸和 max-content 尺寸)。
  • 下面的表格总结了各种 white-space 关键字值的行为:

    默认情况下,一个制表符等于 8 个空格,且可以使用 tab-size 属性。对于 normalnowrappre-line 值,每个制表符都会被转化为一个空格(U+0020)字符。

    空格其他空白分隔符之间存在区别。定义如下:

    空格(U+0020)、制表符(U+0009)和分段符(例如换行)

    其他空白分隔符

    Unicode 中定义的所有其他空格分隔符(已定义为空格的分隔符除外)。

    如果空白字符被挂起,那么它可能会影响框的固有尺寸的测量结果。

    合并空白字符

    white-space-collapse 属性的页面解释了浏览器合并空白字符的算法

    初始值normal
    适用元素所有元素
    是否是继承属性
    计算值as specified
    动画类型离散值
    white-space = 
    normal |
    pre |
    nowrap |
    pre-wrap |
    break-spaces |
    pre-line
    css
    code {
      white-space: pre;
        

    <pre> 元素内的换行

    css
    pre {
      white-space: pre-wrap;