sisterAn / JavaScript-Algorithms

基础理论+JS框架应用+实践,从0到1构建整个前端算法体系
5.45k stars 626 forks source link

CSS 实现文本的单行和多行溢出省略效 #130

Open sisterAn opened 3 years ago

sisterAn commented 3 years ago

单行文本

.text {
  overflow: hidden; 
  text-overflow: ellipsis; 
  white-space: nowrap;
}

多行文本(css)

.text {
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis; 
}

多行文本(js)

Grolia commented 3 years ago

单行:

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

多行(3行)

overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
chpxl2 commented 3 years ago
//1:单行文本溢出
.textTruncate {
     overflow: hidden;
     white-space: nowrap;
     text-overflow: ellipsis;
}

//2:按行数-多行文本溢出(兼容性不好)
.mulLineTruncate {
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
//3:按高度-多行文本溢出(没有省略号)
.mulLineTruncate {
  max-height: 40px;
  overflow: hidden;
  line-height: 20px;
}
//4:解决3方案没有省略号的情况
.mulLineTruncate {
  position: relative;
  max-height: 40px;
  overflow: hidden;
  line-height: 20px;
  &::after {
    position: absolute;
    right: 0;
    bottom: 0;
    padding: 0 20px 0 10px;
    content: '...';
  }
}
fxwing commented 3 years ago
.one-line-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.more-line-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}
ishowman commented 2 months ago
//1:单行文本溢出
.textTruncate {
     overflow: hidden;
     white-space: nowrap;
     text-overflow: ellipsis;
}

//2:按行数-多行文本溢出(兼容性不好)
.mulLineTruncate {
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
//3:按高度-多行文本溢出(没有省略号)
.mulLineTruncate {
  max-height: 40px;
  overflow: hidden;
  line-height: 20px;
}
//4:解决3方案没有省略号的情况
.mulLineTruncate {
  position: relative;
  max-height: 40px;
  overflow: hidden;
  line-height: 20px;
  &::after {
    position: absolute;
    right: 0;
    bottom: 0;
    padding: 0 20px 0 10px;
    content: '...';
  }
}

方案3,如果最后一行字数未达到应该省略显示的条件(例如最后一行只有1个字符),也会显示省略号。并不是很理想的效果