在CSS中,设置换行的方法主要有以下几种:
white-space
属性:控制元素内的空白字符的处理方式。normal
:默认值。空白会被浏览器忽略。nowrap
:文本不会换行,直到遇到<br>
标签为止。pre
:空白符会被保留。pre-wrap
:空白符会被保留,文本会在容器的末尾自动换行。pre-line
:空白符会被合并,文本会在容器的末尾自动换行。
word-wrap
/overflow-wrap
属性:允许长单词或URL地址被打断换行。normal
:只在允许的断字点换行(如空格)。break-word
:在长单词或URL地址内部进行换行。
word-break
属性:指定如何在单词内换行。normal
:使用默认的换行规则。break-all
:允许在单词内换行。keep-all
:CJK(中文/日文/韩文)文字中不允许换行。
实例代码:
/* 设置文本不换行 */
p.no-wrap {
white-space: nowrap;
}
/* 允许在长单词内换行 */
p.break-word {
word-wrap: break-word;
}
/* 合并空白符并自动换行 */
p.wrap-line {
white-space: pre-line;
}
在HTML中使用:
<p class="no-wrap">这段文本不会换行,即使超出容器宽度。</p>
<p class="break-word">这是一个非常非常长的单词wordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordword