跳到主要内容

文本溢出截断

单行文本如何显示省略号?​

  • 三件套: overflow: hidden + text-overflow: ellipsis + white-space: nowrap;
.text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

多行文本如何用高度方案截断?​

  • 建立定位上下文: 父元素 position: relative;
  • 定量: 按行数算 height = line-height × 行数;
  • 省略号: 用 ::after + absolute 定位贴在右下角;
.demo {
position: relative;
line-height: 20px;
height: 40px;
overflow: hidden;
}
.demo::after {
content: "...";
position: absolute;
bottom: 0;
right: 0;
padding: 0 20px 0 10px;
}

多行文本如何用 -webkit-box 截断?​

  • display: -webkit-box: 改为旧版弹性盒;
  • -webkit-box-orient: vertical: 纵向排列;
  • -webkit-line-clamp: 限制显示行数;
  • 配合 overflow/text-overflow/white-space;
.text {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
text-overflow: ellipsis;
white-space: normal;
}