CSS解决文本自动换行

1.单行文本溢出隐藏:

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

2.多行文本溢出隐藏:  (只适用移动端和 chrome)

p{

word-break: break-all;

    text-overflow: ellipsis;    display: -webkit-box;    /** 对象作为伸缩盒子模型显示 **/    -webkit-box-orient: vertical;    /** 设置或检索伸缩盒对象的子元素的排列方式 **/    -webkit-line-clamp: 2;    /** 显示的行数 **/    overflow: hidden;    /** 隐藏超出的内容 **/
}
 

3.跨浏览器的多行文本溢出:

p{
    position: relative;
    line-height: 18px;
    max-height: 36px;
    overflow: hidden;
    &::after {
        content: "...";
        position: absolute;
        bottom: 0;
        right: 0;
        padding-left: 40px;
        background: -webkit-linear-gradient(left, transparent, #fff 55%);
        background: -o-linear-gradient(right, transparent, #fff 55%);
        background: -moz-linear-gradient(right, transparent, #fff 55%);
        background: linear-gradient(to right, transparent, #fff 55%);
    }

注意事项:

  1. height高度真好是line-height的整数倍;
  2. 结束的省略好用了半透明的png做了减淡的效果,或者设置背景颜色;
  3. IE6-7不显示content内容,所以要兼容IE6-7可以是在内容中加入一个标签,比如用<span class="line-clamp">...</span>去模拟;
  4. 要支持IE8,需要将::after替换成:after
  5. 会有不管是否超过都会出现...的bug可通过js调整
4. Clamp.js、 jQuery插件-jQuery.dotdotdot  都可实现
position: relative;
    line-height: 18px;
    max-height: 36px;
    overflow: hidden;
    &::after {
        content: "  ";
        position: absolute;
        bottom: 0;
        right: 0;
        padding-left: 40px;
        background: -webkit-linear-gradient(left, transparent, #fff 55%);
        background: -o-linear-gradient(right, transparent, #fff 55%);
        background: -moz-linear-gradient(right, transparent, #fff 55%);
        background: linear-gradient(to right, transparent, #fff 55%);
    }

猜你喜欢

转载自blog.csdn.net/qq_39643110/article/details/79776265