欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

html文字单行以及多行超出显示省略号

程序员文章站 2022-04-22 13:45:01
...

html文字单行以及多行超出显示省略号

在前端页面中,许多时候需要用到文字超出显示省略号的情况,今天在github上看见一片总结得特别全的文章,列出一下两种较好的方法。
原文链接:https://github.com/libin1991/libin_Blog/issues/372

单行超出显示省略号

单行超出显示省略号可直接使用text-overflow: ellipsis,具体使用参照下面代码,text-overflow: ellipsis兼容所有浏览器,但是只能用于单行文本,它是在不换行的情况下将超出部分使用省略号代替。

<div>
    <p>不是所有的梦都来得及实现,不是所有的话都来得及告诉你</p>
</div>
div {
   margin: 100px;
    width: 200px;
    background: rgb(227, 232, 236);
}

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

html文字单行以及多行超出显示省略号

多行文本超出显示省略号

原理可参考原文

<div class="wrap">
  <div class="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dignissimos labore sit vel itaque delectus atque quos magnam assumenda quod architecto perspiciatis animi.</div>
</div>
.wrap {
  height: 40px;
  line-height: 20px;
  overflow: hidden;
}
.wrap .text {
  float: right;
  margin-left: -5px;
  width: 100%;
  word-break:break-all;
}
.wrap::before {
  float: left;
  width: 5px;
  content: '';
  height: 40px;
}
.wrap::after {
  float: right;
  content: "...";
  height: 20px;
  line-height: 20px;
  padding-right: 5px;
  text-align: right;
  width: 3em;
  margin-left: -3em;
  position: relative;
  left: 100%;
  top: -20px;
  padding-right: 5px;
  /* 显示更好的效果 */
  background: -webkit-gradient(linear, left top, right top, from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white));
  background: -moz-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
  background: -o-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
  background: -ms-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
  background: linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
}

使用float实现多行超出显示省略号,具有兼容性好并且可以做到超出显示省略号,不超出则不显示省略号。