单行文本的省略和多行文本的省略

单行文本的省略

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        p {

            background-color: aqua;

            width: 200px;
            /*设置宽度*/

            white-space: nowrap;
            /*设置空白不换行*/

            text-overflow: ellipsis;
            /*设置省略号*/

            overflow: hidden;
            /*裁剪溢出/多余部分*/

        }
    </style>
</head>

<body>
    <p>
        文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本
    </p>
    <p>
        文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本
    </p>
    <p>
        文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本
    </p>
</body>

</html>

显示效果如下

多行文本的省略

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width: 200px;
            height: 100px;
            overflow: hidden;/* 溢出隐藏 */
            line-height: 20px;/* 设置行高与容器高度成倍数关系,这样避免文本溢出时,文字显示一半 */
            text-align: justify;/* 设置文本对齐方式为两端对齐,这样在伪元素内容遮盖末尾文字时才能对齐*/
            position: relative;/* 子绝父相,这里是为了给伪元素设置定位*/
        }
        .box::after{
            content: "...";/* 省略号是放在文本最后面的 */
            width: 1em;/* 设置伪元素的宽度为1em,是为了遮盖的时候正好遮盖中原来的一个字的大小*/
            background-color: pink;/* 设置与父元素相同的背景颜色,同理,也是为了和原来的内容样式保持一致*/
            position: absolute;/*设置定位,其位置就是文本的右下角 */
            right: 0;bottom: 0;
        }
    </style>
</head>
<body>
    <div class="box">
        文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本
</body>
</html>

显示效果如下

经验分享 程序员 微信小程序 职场和发展