css之多行文本输出

浏览: 186 发布日期: 2016-11-16 分类: css3

css之多行文本输出

需求

本小白拿着设计师给的带标注的设计稿,看到简介标注为只能显示3行文本,多于3行显示3行,本准备采取字符串截取蒙混过关(不能原谅的事情是对自己没有要求,简直没有下限),后查看了网上的解决方案,特此分享。

思路

现在假设想要显示的文本行数是N行,首先设定文本容器的max-height = N 乘以 line-height,第N行显示的文本为部分文本 + ... + 展开全部。设置文本容器的字体颜色为背景色,伪元素before和after的content都为文本内容。借助伪元素before显示(N - 1)行元素,z-index = 1(在文本容器、before伪元素、after伪元素、[展开全部]按钮中确保before伪元素z-index最大)。after伪元素的padding-right宽度为[展开全部]按钮的宽度(单位为em),text-indent = (N - 1) * [展开全部]按钮的宽度(如何理解缩进? 通过设置after伪元素的padding-right为第N行的[展开全部]按钮留位置,由于第1行、第2行...第(N - 1)行都少显示[展开全部]按钮宽度的字体,所以,为了确保伪元素after在第N行中显示正确,需要向左缩进(N - 1) 乘以 [展开全部]按钮的宽度)

效果图

完整代码

<div class="desc" title="Jennifer Joanna Aniston (born February 11, 1969)[1] is an American actress, producer, and businesswoman.[2] The daughter of Greek actor John Aniston and American actress Nancy Dow, Aniston gained worldwide recognition for portraying Rachel Green on the popular television sitcom Friends (1994–2004), a role which earned her a Primetime Emmy Award, a Golden Globe Award, and a Screen Actors Guild Award. The character was widely popular during the airing of the series and was later recognized as one of the 100 greatest female characters in United States television">
        Jennifer Joanna Aniston (born February 11, 1969)[1] is an American actress, producer, and businesswoman.[2] The daughter of Greek actor John Aniston and American actress Nancy Dow, Aniston gained worldwide recognition for portraying Rachel Green on the popular television sitcom Friends (1994–2004), a role which earned her a Primetime Emmy Award, a Golden Globe Award, and a Screen Actors Guild Award. The character was widely popular during the airing of the series and was later recognized as one of the 100 greatest female characters in United States television
   <button>更多</button>
</div>
.desc {
  position: relative;
  width: 400px;
  /*用像素表示,不要用em,以免造成不同浏览器下计算出现小数点取舍不同导致1像素的差距【行高*截取行数】*/
  overflow: hidden;
  max-height: 72px;
  font-size: 16px;
  line-height: 24px;
  overflow: hidden;
  word-wrap: break-word;
  /*强制打散字符*/
  word-break: break-all;
  background: #fff;
  /*同背景色*/
  color: #fff;

  &:after,
  &:before {
    content: attr(title);
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    /*实际文本颜色*/
    color: #000;
  }
  &:before {
    display: block;
    overflow: hidden;
    /*显示在最上面,展示前面的(截取行数-1)行字符*/
    z-index: 1;
    /*根据行高和截取行数调整,值为[(截取行数-1)*行高]*/
    max-height: 48px;
    /*同背景色*/
    background: #fff;
  }
  &:after {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    /*截取行数*/
    -webkit-line-clamp: 3;
    /*行首缩进字符数,值为[(截取行数-1)*尾部留空字符数]*/
    text-indent: -8em;
    /*尾部留空字符数*/
    padding-right: 4em;
  }
  button {
    width: 40px;
    height: 20px;
    font-size: 12px;
    padding: 0;
    outline: 0;
    position: absolute;
    right: 0;
    bottom: 0;
  }
}

参考实例

codepen实例

返回顶部