单行文本溢出,多行文本溢出的省略样式

本文介绍了如何在HTML和CSS中处理单行和多行文本溢出问题,提供了基于高度、行数和JavaScript实现的三种方法,帮助开发者控制文本显示和隐藏省略号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单行文本溢出

效果:

html

 <div>
    你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!
 </div>

css:

  <style>
    div{
      width: 300px;
      border: 1px solid #ccc;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  </style>

多行文本溢出

方法一:基于高度截断

html代码:

<div>
    你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!
    你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!
  </div>

css 代码:

<style>
    div{
      width: 300px;
      border: 1px solid #ccc;
      position: relative;
      overflow: hidden;
      height: 40px;
      line-height: 20px;
    }
    div::after{
      content: '...';
      position: absolute;
      bottom: 0;
      right: 0;
    }
  </style>
方法二:基础行数截断【纯CSS】

html同上

css 代码

<style>
    div{
      width: 300px;
      border: 1px solid #ccc;
      -webkit-line-clamp: 2;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  </style>

方法二:基础行数截断【JS实现】

css 代码

<style>
    p{
      width: 300px;
      border: 1px solid #ccc;
      position: relative;
      overflow: hidden;
      line-height: 20px;
    }
    
    .p-after::after {
      content: '...';
      position: absolute;
      bottom: 0;
      right: 0;
      background: -webkit-linear-gradient(left, transparent, #fff 50%);
      background: linear-gradient(to right, transparent, #fff 55%);
    }
  </style>

js 代码

<script>
    (function () {
      const divEl = document.getElementsByTagName('p')[0];
      var lineHeightPro = window.getComputedStyle(divEl).getPropertyValue('line-height');
      var lineHeight = lineHeightPro.substring(0, lineHeightPro.indexOf('p'));
      var heightPro = window.getComputedStyle(divEl).getPropertyValue('height');
      var height = heightPro.substring(0, heightPro.indexOf('p'));
      if ((parseInt(height) / parseInt(lineHeight)) > 3) {
        divEl.classList.add('p-after');
        divEl.style.height = '60px';
      } else {
        divEl.classList.remove('p-after');
      }
    })()
  </script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值