CSS text-overflow 属性控制如何向用户显示隐藏的溢出内容。它可以被修剪,具有省略号 ('...'),或显示自定义字符串。
此属性通常用于文本可能由于空间有限而被截断的情况,例如在固定宽度的容器或单行文本中。
text-overflow 属性不会导致溢出。您需要指定 CSS 属性 overflow 和 white-space,以导致文本溢出到其容器之外。
overflow: hidden;
white-space: nowrap;
可能的值
- clip - 默认值。此关键字值在内容区域限制处截断文本,可能在字符的中间;如果支持,请使用 text-overflow: '' 在字符过渡处进行剪辑。
- 省略号 − 此关键字值在内容区域内显示省略号(“...”,U+2026 水平省略号),以显示剪裁的文本,减少可见文本并在空间有限时剪裁省略号。
- 字符串 − 此值允许您指定一个自定义字符串,用作截断文本的指示符。例如,text-overflow: “...”将使用三个点 (...) 作为指示器。
这仅在Firefox浏览器中有效。
适用于
块容器元素。
语法
text-overflow: clip | ellipse;
text-overflow 属性采用一个值并为行的末端设置溢出行为,而两个值指示左端和右端的行为,允许使用关键字(剪辑或省略号)或 <string>值。
CSS text-overflow - 一个语法值
以下示例演示了如何使用具有不同值的 text-overflow 属性,包括从左到右和从右到左的文本 -
<html>
<head>
<style>
body {
display: flex;
justify-content: space-around;
}
p {
width: 200px;
border: 1px solid;
padding: 2px 5px;
white-space: nowrap;
overflow: hidden;
}
.box1 {
text-overflow: clip;
}
.box2 {
text-overflow: ellipsis;
}
.box3 {
text-overflow: "***";
}
.left-right > p {
direction: ltr;
}
.right-left > p {
direction: rtl;
}
</style>
</head>
<body>
<div class="left-right">
<h2>Left to right text</h2>
<h3>clip</h3>
<p class="box1">
Tutorialspoint CSS text-overflow: clip.
</p>
<h3>ellipsis</h3>
<p class="box2">
Tutorialspoint CSS text-overflow: ellipsis.
</p>
<h3>"***" (Open is Firefox to see this effective)</h3>
<p class="box3">
Tutorialspoint CSS text-overflow: "***".
</p>
</div>
<div class="right-left">
<h2>Right to left text</h2>
<h3>clip</h3>
<p class="box1">
Tutorialspoint CSS text-overflow: clip
</p>
<h3>ellipsis</h3>
<p class="box2">
Tutorialspoint CSS text-overflow: ellipsis.
</p>
<h3>"***"</h3>
<p class="box3">
Tutorialspoint CSS text-overflow: "***".
</p>
</div>
</body>
</html>
CSS text-overflow - 双值语法
以下示例演示如何使用双值语法进行文本溢出,从而允许在文本的开头和结尾使用不同的溢出行为。要查看效果,还需要滚动以隐藏行的开头 -
打开是 Firefox 以查看此示例有效
<html>
<head>
<style>
p {
width: 200px;
border: 1px solid;
padding: 5px;
white-space: nowrap;
overflow: scroll;
}
.box1 {
text-overflow: clip clip;
}
.box2 {
text-overflow: clip ellipsis;
}
.box3 {
text-overflow: ellipsis ellipsis;
}
.box4 {
text-overflow: ellipsis "***";
}
</style>
</head>
<body>
<h3>clip clip</h3>
<p class="box1">
Contrary to popular belief, Lorem Ipsum is not simply random text.
</p>
<h3>clip ellipsis</h3>
<p class="box2">
Contrary to popular belief, Lorem Ipsum is not simply random text.
</p>
<h3>ellipsis ellipsis</h3>
<p class="box3">
Contrary to popular belief, Lorem Ipsum is not simply random text.
</p>
<h3>ellipsis "***"</h3>
<p class="box4">
Contrary to popular belief, Lorem Ipsum is not simply random text.
</p>
<script>
const paras = document.querySelectorAll("p");
for (const para of paras) {
para.scroll(100, 0);
}
</script>
</body>
</html>