CSS - text-overflow 属性



CSS 的text-overflow 属性控制如何向用户显示隐藏的溢出内容。它可以被修剪、显示省略号 ('…') 或显示自定义字符串。

此属性通常用于文本可能因空间有限而被截断的情况,例如在固定宽度容器或单行文本中。

text-overflow 属性不会导致溢出。您需要指定 CSS 属性overflowwhite-space 才能使文本溢出其容器。

overflow: hidden; white-space: nowrap;

可能的值

  • clip − 默认值。此关键字值在内容区域限制处截断文本,可能在字符中间;如果支持,请使用text-overflow: '' 在字符转换处剪辑。

  • ellipsis − 此关键字值在内容区域内显示省略号 ('…', U+2026 HORIZONTAL ELLIPSIS) 以显示被剪辑的文本,减少可见文本并在空间有限时剪辑省略号。

  • string − 此值允许您指定要用于截断文本指示符的自定义字符串。例如,text-overflow: "..." 将使用三个点 (...) 作为指示符。

    这仅在 Firefox 浏览器中有效。

应用于

块级容器元素。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

语法

text-overflow: clip | ellipse;

text-overflow 属性采用一个值并设置行的结束处的溢出行为,而两个值则指示左右两端的行为,允许使用关键字 (clipellipsis) 或<string> 值。

CSS text-overflow - 单个语法值

以下示例演示如何使用text-overflow 属性的不同值,包括从左到右和从右到左的文本:

Open Compiler
<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 - 双值语法

以下示例演示如何使用text-overflow 的双值语法,允许在文本开头和结尾处使用不同的溢出行为。要查看效果,需要滚动以隐藏行的开头:

在 Firefox 中打开以查看此示例有效
Open Compiler
<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>
广告