在HTML中要创建一个没有
<br>
标签的换行,可以将文本容器的
white-space
属性设置为
pre-wrap
。例如:
HTML
<div id\="box"\>
Lorem Ipsum
Lorem Ipsum
Lorem Ipsum
</div\>
CSS
#box {
white-space: pre-wrap;
}
设置
line-space
为
pre
可以保留元素文本中的换行和空格序列。因此,第一行中单词之间的4个空格也随着换行一起显示出来。
请注意,用于文本缩进的空格也会在输出中显示,给容器添加额外的左内边距。
使用
white-space: pre-wrap
换行
当
white-space
设置为
pre-wrap
时,还可以通过包含
\\n
字符来显示换行,将该字符分配给
[innerHTML](<https:///en-US/docs/Web/API/Element/innerHTML>)
或
[innerText](<https:///en-US/docs/Web/API/HTMLElement/innerText>)
属性。
JavaScript
const box = document.getElementById('box');
box.innerText = 'JavaScript tutorial at \\n Coding Beauty';
没有
white-space: pre-wrap
时,输出将如下:
使用
white-space: pre
换行
我们还可以使用
white-space
属性将其设置为
pre
,以显示没有
<br>
标签的换行。
pre
与
pre-wrap
的行为非常相似,但文本不会像
pre-wrap
或默认值
normal
一样自动换行。
例如,让我们将
#box
容器的宽度减少到
200px
,以观察其使用
pre
的溢出行为。
HTML
<div id\="box"\>
JavaScript at Coding Beauty
HTML at Coding Beauty
CSS at Coding Beauty
</div\>
CSS
#box {
white-space: pre;
background-color: #e0e0e0;
width: 200px;
}
如果
pre
在这个示例中是
pre-wrap
:
当通过JavaScript将元素的
[innerHTML](<https:///en-US/docs/Web/API/Element/innerHTML>)
或
[innerText](<https:///en-US/docs/Web/API/HTMLElement/innerText>)
属性设置为字符串时,
pre
的行为也是相同的。
使用
white-space: pre-line
换行
在您希望额外的空格被忽略,但换行符在输出中显示时,将
white-space
设置为
pre-line
会派上用场。
以宽度为300px和
white-space
为
pre-line
的情况下,将如下所示:
HTML
JavaScript at Coding Beauty HTML at Coding Beauty CSS at Coding Beauty
CSS
#box {
white-space: pre-line;
background-color: #e0e0e0;
width: 300px;
}
宽度为200px时:
与之前的两个可能的
white-space
值一样,当使用JavaScript将元素的innerHTML或innerText属性设置为字符串时,
pre-line
的行为也是相同的。