-webkit-line-clamp属性
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>多行文本溢出省略</title>
<style>
.text-container {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3; /* 设置你希望显示的最大行数 */
overflow: hidden;
text-overflow: ellipsis;
white-space: normal;
word-wrap: break-word;
max-width: 100%; /* 确保内容不会超出容器 */
}
</style>
</head>
<body><div class="text-container">
这里是一段用于测试的多行文本。当你将这段文本放入一个设置了特定宽度和高度限制的容器中时,如果文本内容超出了这个容器的容量,超出部分将会被隐藏,并在最后显示省略号(...)。
</div></body>
</html>
依赖 `-webkit` 前缀,兼容性有限(不支持 IE 浏览器)。
css伪元素
代码如下
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>多行文本溢出省略</title>
<style>
.text-container {
width: 300px; /* 设置你希望的宽度 */
line-height: 1.5em; /* 根据字体大小调整行高 */
max-height: 4.5em; /* 行高乘以你想显示的最大行数(此处为3行) */
overflow: hidden;
position: relative;
display: block;
word-wrap: break-word;
}/* 添加省略号 */
.text-container::after {
content: "...";
font-weight: bold;
position: absolute;
bottom: 0;
right: 10px;
background: white; /* 背景颜色应与容器背景色相同 */
padding-left: 3px; /* 调整省略号和文本之间的距离 */
pointer-events: none; /* 确保省略号不会影响鼠标事件 */
}/* 隐藏省略号后方的内容 */
.text-container::before {
content: "";
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 1em; /* 控制遮挡范围 */
background: white; /* 背景色应与页面背景色相同 */
right: 0;
}
</style>
</head>
<body><div class="text-container">
这里是一段用于测试的多行文本。当你将这段文本放入一个设置了特定宽度和高度限制的容器中时,如果文本内容超出了这个容器的容量,超出部分将会被隐藏,并在最后显示省略号(...)。
</div></body>
</html>
效果
兼容性较好,支持更多浏览器(包括 IE),需要根据实际手动调整css。
使用 JavaScript 动态计算
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>多行文本溢出省略</title>
<style>
.text-container {
width: 300px;
line-height: 1.5em;
max-height: 4.5em;
overflow: hidden;
word-wrap: break-word;
}
</style>
</head>
<body>
<div class="text-container" id="text">
这里是一段用于测试的多行文本。当你将这段文本放入一个设置了特定宽度和高度限制的容器中时,如果文本内容超出了这个容器的容量,超出部分将会被隐藏,并在最后显示省略号(...)。
</div><script>
function truncateText(element, maxLines) {
const lineHeight = parseInt(window.getComputedStyle(element).lineHeight, 10);
const maxHeight = lineHeight * maxLines;
let text = element.innerText;while (element.scrollHeight > maxHeight) {
text = text.slice(0, -1);
element.innerText = text + '...';
}
}const textElement = document.getElementById('text');
truncateText(textElement, 3);
</script>
</body>
</html>
依赖 JavaScript,性能较差,不适合大量文本。