Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sisterAn opened this issue Nov 19, 2020 · 3 comments
Open

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

sisterAn opened this issue Nov 19, 2020 · 3 comments

Comments

@sisterAn
Copy link
Owner

sisterAn commented Nov 19, 2020

单行文本

.text {
  overflow: hidden; 
  text-overflow: ellipsis; 
  white-space: nowrap;
}
  • overflow: hidden(文字长度超出限定宽度,则隐藏超出的内容)
  • white-space: nowrap(设置文字在一行显示,不能换行)
  • text-overflow: ellipsis(规定当文本溢出时,显示省略符号来代表被修剪的文本)

多行文本(css)

.text {
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis; 
}
  • -webkit-line-clamp: 2(用来限制在一个块元素显示的文本的行数, 2 表示最多显示 2 行。 为了实现该效果,它需要组合其他的WebKit属性)
  • display: -webkit-box(和 1 结合使用,将对象作为弹性伸缩盒子模型显示 )
  • -webkit-box-orient: vertical(和 1 结合使用 ,设置或检索伸缩盒对象的子元素的排列方式 )
  • overflow: hidden(文本溢出限定的宽度就隐藏内容)
  • text-overflow: ellipsis(多行文本的情况下,用省略号“…”隐藏溢出范围的文本)

多行文本(js)

  • 监听DOM尺寸变化
  • 判断是否溢出 scrollHeight > offsetHeight
  • 二分查找多行截取字符临界值(算法的解法:判断字符串是否溢出,二分查找字符串溢出临界子串,控制...显示)
@sisterAn sisterAn changed the title 字节:CSS 实现文本的单行和多行溢出省略效 CSS 实现文本的单行和多行溢出省略效 Nov 19, 2020
@Grolia
Copy link

Grolia commented Nov 20, 2020

单行:

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
Copy link

chpxl2 commented Nov 20, 2020

//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
Copy link

fxwing commented Dec 7, 2020

.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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants