Skip to content

white-space 各种用法

white-space: normal

This is a test with some very long text to demonstrate line wrapping behavior of the white-space property.

white-space: nowrap

This is a test with some very long text to demonstrate line wrapping behavior of the white-space property.

white-space: pre

This is a test with some very long text to demonstrate line wrapping behavior of the white-space property.

white-space: pre-wrap

This is a test with some very long text to demonstrate line wrapping behavior of the white-space property.

white-space: pre-line

This is a test with some very long text to demonstrate line wrapping behavior of the white-space property.
html
<div style="white-space: normal; border: 1px solid #000; width: 200px;">This   is    a    test    with    some    very    long    text    to    demonstrate    line    wrapping    behavior    of    the    white-space    property.</div>

<div style="white-space: nowrap; border: 1px solid #000; width: 200px;">This   is    a    test    with    some    very    long    text    to    demonstrate    line    wrapping    behavior    of    the    white-space    property.</div>

<div style="white-space: pre; border: 1px solid #000; width: 200px;">This   is    a    test    with    some    very    long    text    to    demonstrate    line    wrapping    behavior    of    the    white-space    property.</div>

<div style="white-space: pre-wrap; border: 1px solid #000; width: 200px;">This   is    a    test    with    some    very    long    text    to    demonstrate    line    wrapping    behavior    of    the    white-space    property.</div>

<div style="white-space: pre-line; border: 1px solid #000; width: 200px;">This   is    a    test    with    some    very    long    text    to    demonstrate    line    wrapping    behavior    of    the    white-space    property.</div>

每个<div>元素都被设置了一个固定的宽度,并用不同的white-space属性值

  • normal:在这个例子中,所有空格被合并为一个空格,文本在需要的地方自动换行。
  • nowrap:所有空格被合并为一个空格,但文本不会自动换行,因此你会看到文本超出了容器的边界。
  • pre:保留了所有的空格,并保持了源代码中的换行,但文本不会自动换行,因此文本会超出容器边界。
  • pre-wrap:保留了所有的空格和换行,文本也会在需要的地方自动换行。
  • pre-line:保留了换行,但所有连续的空格被合并为一个空格,文本在需要的地方自动换行。