支持多浏览器的纯 CSS 多行文本溢出省略号「转」

Posted ·714 Views·838 Words

单行文本溢出省略号一般我们都知道实现方法。

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

那么如果多行文本应该怎么做呢,伟大的chrome 又走在了时代前沿,可以使用-webkit-line-clamp这个属性来实现,这个属性已经有年头了,但是其他浏览器仍然不支持,一声叹息。

.xxx {
    display:-webkit-box;
    -webkit-line-clamp:2;
    -webkit-box-orient:vertical;
    overflow:hidden;
}

-webkit-line-clamp 为行数,如果显示3行,则设置为3即可。

悲剧的是-webkit-line-clamp只有webkit 内核支持,于是我们要想办法解决这个问题,纯css 完美实现是不显示了,只能优雅降级,可以使用下面的方案,把最大高度设置为n倍行高,然后溢出部分隐藏即可。

.xxx {
    line-height: 1.2;
    max-height: 2.4em;
    overflow: hidden;
}

这样做的好处是可以忽略文本的长度,即使文本很短不会出现问题。如果确定文本是肯定溢出的,还可以使用::after 伪类来模拟…

大致代码

.xxx {
    line-height: 1.2;
    max-height: 2.4em;
    overflow: hidden;
    position: relative;
}
.xxx:after {
    content:"...";
    position:absolute;
    bottom: 0;
    right: 0;
    background-color: #fff;
}

考虑到文本不一定会溢出,最终的解决方案推荐:

.xxx {
    line-height: 1.2;
    max-height: 2.4em;
    display:-webkit-box;
    -webkit-line-clamp:2;
    -webkit-box-orient:vertical;
    overflow:hidden;
}

全文完。

Comments

Leave a comment to join the discussion