纯css实现文本内容单行/多行溢出显示省略号

纯css实现文本内容单行/多行溢出显示省略号_第1张图片

一般都知道css可以实现单行溢出限制,那么多行溢出的话,css该怎么去实现了,此例主要借助css的伪元素样式去实现的,具体代码和注释如下。

单行超出宽度限制溢出

html代码:

<div class="text">
  css实现单行宽度限制溢出时出现省略号
div>

css代码:

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

浏览器渲染效果:

纯css实现文本内容单行/多行溢出显示省略号_第2张图片

多行超出限制溢出(敲黑板!)

html代码:

<div class="text">
  多行超出宽度限制溢出时出现省略号多行超出宽度限制溢出时出现省略号多行超出宽度限制溢出时出现省略号多行超出宽度限制溢出时出现省略号多行超出宽度限制溢出时出现省略号多行超出宽度限制溢出时出现省略号多行超出宽度限制溢出时出现省略号
div>

css代码:

.text{
  width: 240px;
  overflow: hidden; /*文字超出时隐藏*/
  text-overflow: ellipsis; /*文本溢出时,显示省略符号*/
  word-break: break-all; /*英文自动换行*/

  /*webkit私有属性,仅支持webkit核*/
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;  /*显示行数*/

  /*根据行高来限制高度*/
  line-height: 1.5;
  height: 4.5em; /*高度等于行高的3倍*/

  position: relative; /*配合 .text:after 定位使用*/
}
.text:after{
  content: '...';
  position: absolute;
  bottom: 0;
  right: 0;
  line-height: 1.5;
  padding: 0 2px;
  background-color: #e2e2e2; /*统一背景*/
}

浏览器渲染效果:

纯css实现文本内容单行/多行溢出显示省略号_第3张图片

你会发现多行溢出的css代码部分比较多,这是为了兼容非webkit核的浏览器。

在移动端来说大部分手机浏览器都是webkit核的,所以也同样兼容手机上显示。


​​[1] 阅读原文​​

[2] 我是Just,订阅号[ 设计师工作日常 ],求点赞求关注!!!skr~ skr~

你可能感兴趣的:(前端的诱惑,css,css3,前端,html)