2011
Sep
03

CSS 文字换行的 style 为 word-wrap ,透过这个属性可以指定换行的方式,并可以强制文字不换行。

而 CSS 还有个空白长度的设定,透过 white-space 可以移除连续空白。

  • 文字强迫换行,英文字会被切一半 word-break: break-all;
  • 依单字换行 word-wrap:break-word;
  • 死都不换行 white-space:nowrap;

换行设定, word-wrap & word-break

文字强迫换行,太长的英文字,会自动切成两半。
  • word-break: break-all; 若一个单字过长,超过画面的宽度,则将单字切断,并换行。

word-break: break-all;
Before Moammar Long language string Long language string Long language string Long language string, there were the Phoenicians.

从上面的 DEMO 中可以看到 language 这个单字被切成两断。

文字自动换行,长英文字不切断

  • word-wrap:break-word; 若一个单字过长,超过画面的宽度,则将单字换行(不切断单字)。

word-wrap:break-word;
Before Moammar Long language string Long language string Long language string Long language string, there were the Phoenicians.

不切断英字单字对於一般的读者是比较好懂的,唯一的缺点是右边会出现很大的一块空白。

空白设定 : white-space

保留原始空白与换行
  • white-space:pre; 保留原始资料的空白与换行,功能与 HTML tag 中的 <pre> 相同。
white-space:pre;
Before Moammar Gadhafi, there were the Phoenicians. And the Greeks.

强迫文字不换行

  • white-space:nowrap; 移除连续空白,移除换行符号(n r), 强迫文字不换行。
white-space:nowrap;
Before Moammar Gadhafi, there were the Phoenicians. And the Greeks.

保留原始空白,但文字自动换行

  • white-space:pre-wrap; 保留所有空白,自动换行。
white-space:pre-wrap;
Before Moammar Gadhafi, there were the Phoenicians. And the Greeks. The Romans.

连续空白,取代成一个空白。

  • white-space: pre-line ,这个语法可以会自动将多个空白转换成一个空白
white-space: pre-line;
Before Moammar Gadhafi, there were the Phoenicians. And the Greeks. The Romans.

目前回應 Comments(3 comments)

  • Lykoi 2022/04/09

    感謝整理

  • poppy 2021/05/14

    非常實用XD 看到死都不換行就笑了

  • Facy 2019/06/06

    很棒的整理:P

回應 (Leave a comment)