word-break, word-wrap和white-space
一直以来对于word-break,word-wrap和white-space这三个css属性的作用不是很清楚,不知道对于文字换行的属性为什么需要使用3个样式,每次碰到需要换行或不换行时就需要拼命回忆,然后试着组合使用,以至于对这三个属性的区别越来越迷糊,今天准备一次性解决这个问题。
请看jsfiddle里对word-wrap和word-break的比较。
word-wrap
定义:
The word-wrap property allows long words to be able to be broken and wrap onto the next line. 此属性允许长单词被截断到下一行。
语法:
word-wrap: normal(default)|break-word; 各主流浏览器都支持
值 | 描述 |
---|---|
normal | Break words only at allowed break points 只在允许的断字点换行(浏览器保持默认处理) |
break-word | Allows unbreakable words to be broken 在长单词或 URL 地址内部进行换行 |
说明:
对于正常的英文语句,当一行中最后一个单词的长度超过剩余的宽度时,浏览器会将此单词放到下一行,而当碰到很长的单词或者很长的链接时,一个单词的长度就超过一行的宽度,这时候,默认值normal允许文字超出父元素
word-break
定义:
The word-break property specifies line breaking rules for non-CJK scripts. CJK scripts are Chinese, Japanese and Korean (“CJK”) scripts. 对亚洲字符有效
语法:
word-break: normal(default)|break-all|keep-all;各主流浏览器都支持
值 | 描述 |
---|---|
normal | Break words according to their usual rules 使用浏览器默认的换行规则。 |
break-all | Lines may break between any two letters 亚洲字符,和normal效果一样;非亚洲字符,在任意字符换行。 |
keep-all | Breaks are prohibited between pairs of letters 对亚洲字符,不换行。非亚洲字符,和normal效果一样 |
说明:
normal值使用浏览器默认的行规则。 break-all值分两种情况,对亚洲字符,和normal效果一样;非亚洲字符则在任意字符截断。keep-all值也分两种情况,对亚洲字符,不换行;非亚洲字符,和normal效果一样。
比较jsfiddle例子中7和8,可以知道word-wrap:break-word和word-break:break-all的区别。
white-space
定义:
The white-space property specifies how white-space inside an element is handled. white-space 属性设置如何处理元素内的空白。值 pre-wrap 和 pre-line 是 CSS 2.1 中新增的。
语法:
white-space:normal(default)|nowrap|pre|pre-line|pre-wrap|inherit;
Value | Description |
---|---|
normal | Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary. This is default 空白会被合并成一个,文字在需要时会自动换行,此为默认值 |
nowrap | Sequences of whitespace will collapse into a single whitespace. Text will never wrap to the next line. The text continues on the same line until a <br /> tag is encountered 空白会被合并成一个,文字不会换行,直到遇到下一个<br/> |
pre | Whitespace is preserved by the browser. Text will only wrap on line breaks Acts like the <pre> tag in HTML 空白会被保留,文字只在遇到换行符时换行。同<pre/> 标签表现相同。 |
pre-line | Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary, and on line breaks 空白被合并成一个,文字在需要时会自动换行,但是保留换行符。 |
pre-wrap | Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks 空白被保留,文字在需要时自动换行,同时保留换行符。 |
inherit | Specifies that the value of the white-space property should be inherited from the parent element 从父元素继承。 |
说明:
white-space比较好理解,比较常用的是nowrap属性,强制不换行。
luckyGirl - 2014 年 1 月 20 日 1:13 下午
嗯 我也经常弄不清楚这三个属性,模糊记得这三个的浏览器兼容性是不一样的