css单行文本和多行文本溢出实现省略号显示

1、单行文本溢出

 文本内容

<div class="singleLine">                   
  HelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorld
</div>

固定文本宽度,且保证文本不换行,溢出的部分隐藏,设置text-overflow为ellipsis则溢出的文本以省略号显示

.singleLine{ 
  width:200px;
  padding: 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

显示效果如图

2、多行文本溢出

 文本内容

<div class="multiLine">
    HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld
</div>

多行文本显示时通过-webkit-line-clamp设置显示的行数,并且设置display为-webkit-box,-webkit-box-orient为vertical

.multiLine{ 
  width:200px; 
  padding:0 10px;
  overflow : hidden; 
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical; 
}

显示效果

 3、跨浏览器

.imitate_ellipsis{
  position:relative;
  line-height:1.4em;
  height:2.8em;
  overflow:hidden;
  width:200px; 
}
.imitate_ellipsis::after{
  content:"...";
  font-weight:bold;
  position:absolute;
  bottom:0;
  right:0;
  padding-left:20px;
  background: -webkit-linear-gradient(left, transparent, #fff 0%);
  background: -o-linear-gradient(right, transparent, #fff 0%);
  background: -moz-linear-gradient(right, transparent, #fff 0%);
  background: linear-gradient(to right, transparent, #fff 0%);
}

通过伪类::after在文本后加入省略号

posted @ 2018-08-06 15:23  慵懒的小猪  阅读(202)  评论(0编辑  收藏  举报