css3 属性 text-overflow 实现截取多余文字内容 以省略号来代替多余内容

css3 属性 text-overflow: ellipsis

前言

我们在设计网站的时候有时会遇到这样一个需求:因为页面空间大小的问题,需要将多余的文字隐藏起来,并以省略号代替,类似这样的效果:
在这里插入图片描述
做到这样的效果,我们需要运用两个特殊的样式来实现 text-overflow 和 white-space

正文

让我们分别来看一下使用了这些样式,和不使用这些样式的区别吧

  • html内容
<div class="box">
    <span>我是一段测试文本1我是一段测试文本2我是一段测试文本3我是一段测试文本4我是一段测试文本5我是一段测试文本5</span>
</div>

1. 不使用特殊样式

  • 样式内容
.box{
    background: red;
    width: 100px;
}

  • 效果展示
    在这里插入图片描述
    我们可以看到,文本根据边框的宽度,自动换行,并且全部显示

2. 使用 white-space: nowrap 样式

  • 样式内容
.box{
    background: red;
    width: 100px;
    white-space: nowrap;             /*使文本内容不换行,写在一行*/
}
  • 效果图
    在这里插入图片描述
    3. 使用white-space: nowrap和overflow:hidden样式
  • 样式内容
.box{
    background: red;
    width: 100px;
    white-space: nowrap;             /*使文本内容不换行,写在一行*/
    overflow: hidden;                /*隐藏多余内容*/
}
  • 效果图
    在这里插入图片描述
    4. 使用white-space: nowrap和overflow:hidden和text-overflow: ellipsis 样式
  • 样式内容
.box{
    background: red;
    width: 100px;
    white-space: nowrap;             /*使文本内容不换行,写在一行*/
    overflow: hidden;                /*隐藏多余内容*/
    text-overflow: ellipsis;         /*将多余内容以省略号的方式展示*/
}
  • 效果图
    在这里插入图片描述

结束语

希望这篇文章对大家能有所帮助

猜你喜欢

转载自blog.csdn.net/l_ppp/article/details/105898964