CSS(Cascading Style Sheets)是一种用于描述HTML或XML(包括SVG、MathML等各种XML方言)文档样式的样式表语言。CSS控制文本自动换行主要是通过white-space
、word-wrap
(或overflow-wrap
)、text-overflow
等属性来实现的。
white-space
:normal
:默认值,空白会被浏览器忽略。nowrap
:文本不会换行,直到遇到<br>
标签。pre
:空白会被浏览器保留,行为方式类似HTML的<pre>
标签。pre-wrap
:保留空白符序列,但是文本会换行。pre-line
:合并空白符序列,但是文本会换行。word-wrap
/overflow-wrap
:normal
:只在允许的断字点换行。break-word
:在长单词或URL地址内部进行换行。text-overflow
:clip
:超出部分被裁剪。ellipsis
:超出部分显示为省略号。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Text Wrapping</title>
<style>
.container {
width: 200px;
border: 1px solid black;
white-space: pre-wrap;
word-wrap: break-word;
text-overflow: ellipsis;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
</head>
<body>
<div class="container">
This is a long text that needs to be wrapped automatically to fit within the container.
</div>
</body>
</html>
word-wrap: break-word
。word-wrap: break-word
。text-overflow: ellipsis
和其他相关属性。text-overflow: ellipsis
,并且容器有固定的宽度或最大宽度。通过以上方法,可以有效解决CSS控制文本自动换行时遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云