CSS 实现多行文本省略号+展开效果

149 阅读1分钟

平时开发会有要求一段文本超过一定行数要展示省略号+展开收起效果的需求,今天用 css 来实现一个这样的效果。

首先看下 html 代码

<div class="wrap">
    <p class="content">
        <span class="spread">展开</span>
        过零丁洋 <br />
        辛苦遭逢起一经,干戈寥落四周星。山河破碎风飘絮,身世浮沉雨打萍。
        惶恐滩头说惶恐,零丁洋里叹零丁。人生自古谁无死?留取丹心照汗青。
    </p>
</div>

再看下 css 代码

<style>
    .wrap {
        display: flex;
    }

    .content {
        font-size: 15px;
        overflow: hidden;
        text-align: justify;
        position: relative;
        line-height: 24px;
        max-height: 72px;
    }

    .content::before {
        content: '';
        height: calc(100% - 24px);
        float: right;
        width: 0;
    }

    .content::after {
        content: '';
        width: 100vw;
        height: 24px;
        position: absolute;
        background-color: #fff;
        z-index: 99;
    }

    .spread {
        position: relative;
        float: right;
        clear: both;
        margin-left: 20px;
        font-size: 15px;
    }

    .spread::before {
        content: '...';
        position: absolute;
        left: -20px;
        color: #000;
    }
</style>

最后看下实现效果

截屏2023-08-25 15.19.18.png