CSS文字省略号(Text Ellipsis)是一种CSS属性,用于在文本溢出其容器时显示省略号(...),而不是显示整个文本。这在设计中常用于保持布局的一致性和美观性。
CSS文字省略号主要通过以下三个属性实现:
text-overflow: ellipsis;:指定当文本溢出时应显示省略号。white-space: nowrap;:防止文本换行。overflow: hidden;:隐藏溢出的文本。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Text Ellipsis Example</title>
<style>
.ellipsis {
width: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
</head>
<body>
<div class="ellipsis">
This is a very long text that will be truncated with an ellipsis.
</div>
</body>
</html>原因:
text-overflow: ellipsis; 必须在 overflow: hidden; 和 white-space: nowrap; 之后设置。解决方法:
.ellipsis {
width: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}原因: CSS本身不直接支持多行文本省略号,但可以通过一些技巧实现。
解决方法: 使用伪元素和绝对定位来实现多行文本省略号。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multi-line Text Ellipsis Example</title>
<style>
.ellipsis {
width: 200px;
overflow: hidden;
position: relative;
}
.ellipsis::after {
content: '...';
position: absolute;
bottom: 0;
right: 0;
background: white;
padding-left: 4px;
}
.ellipsis > span {
display: block;
overflow: hidden;
white-space: nowrap;
}
</style>
</head>
<body>
<div class="ellipsis">
<span>This is a very long text that will be truncated with an ellipsis.</span>
</div>
</body>
</html>CSS文字省略号是一种强大的工具,用于在文本溢出时保持布局的整洁和美观。通过合理使用 text-overflow, white-space, 和 overflow 属性,可以实现单行和多行文本的省略号效果。
没有搜到相关的文章