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 实现文本溢出省略效果 #49

Open
liangbus opened this issue Apr 23, 2020 · 0 comments
Open

纯 CSS 实现文本溢出省略效果 #49

liangbus opened this issue Apr 23, 2020 · 0 comments

Comments

@liangbus
Copy link
Owner

liangbus commented Apr 23, 2020

单行

.single-line{
  width: 300px;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}

优点:
兼容性好
不会切割单个文字
简洁代码少

缺点:
无法实现多行

多行 (-webkit)

以下这个是使用了 webkit 提供的方法,在 Chrome 上使用完全没有问题

.multi-lines{
  width: 400px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

优点:
代码简洁
兼容多行
不会切割单个文字
代码简洁

缺点:
兼容性不好,除 Chrome 外的浏览器不支持

多行(兼容版本)

利用伪类标签,同时设置 before 和 after 然后,其中 after 宽度设置100%,并且 z-index 比 before 高,这样当文字末行没有顶到末端的话,after 会遮挡 before 的 content 值,从而实现只有文字溢出才会出现 ...

.ellipsis{
  font-size: 18px;
  position: relative;
  width: 400px;
  line-height: 28px;
  height: 110px;
  overflow: hidden;
}
.ellipsis::before{
  content: "...";
  position: absolute;
  bottom: 0;
  width: 1em;
  right: 4px;
  line-height: 20px;
  background-color: #fff;
  z-index: 1;
}
.ellipsis::after{
  content: "";
  position: absolute;
  width: 100%; 
  height: 20px; 
  background-color: #fff; 
  z-index: 2;
}

优点:
大部分浏览器都支持,em 值也可以改成特定的像素值,可以兼容更低版本

缺点:
代码量大,比较复杂
会切割文字,文字可能会被切掉一边

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

No branches or pull requests

1 participant