CSS实现文本溢出

奴止
Sep 30, 2022
Last edited: 2022-10-8
type
Post
status
Published
date
Sep 30, 2022
slug
css-text-overflow
summary
纯 CSS 实现一些常见的文本溢出样式。
tags
前端开发
CSS
category
技术随手记
icon
password
Property
Oct 8, 2022 02:40 PM
 
记录如下 4 中文本溢出解决方案(文末有在线示例):
溢出处理效果截图
溢出处理效果截图

末尾打点

 

单行

 
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;

多行(webkit支持)

 
overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2;
 

全兼容

💡
说明:未溢出时,纯色区块覆盖省略号区块,实现省略号自动隐藏;溢出时,纯色区块被挤出可视区。
 
.ellipsis-3 { .multiLineEllipsis(1.2em, 3); // 仅展示 3 行 } .multiLineEllipsis(@lineHeight: 1.2em, @lineCount: 1, @bgColor: white){ overflow: hidden; position: relative; line-height: @lineHeight; word-break: break-all; max-height: @lineHeight * @lineCount; &:before { content: '...'; position: absolute; right: 0; bottom: 0; padding-left: 2em; padding-right: 0.4em; background: linear-gradient(to right, transparent, white 55%); } &:after { content: ''; position: absolute; right: 0; width: 1em; height: 1em; margin-top: 0.2em; background: @bgColor; } }

中间打点

 
单行文本溢出,省略号位于中间。
 
DOM 结构:
<div class="ellipsis ellipsis-4"> <span class="left">这是文本溢出示例,这是文本溢出示例,这是文本溢出示例,这是文本</span> <span class="right">。溢出示例</span> </div>
 
⚠️
关键点: 1. 左边正常打点,并留出右边要展示的文字的宽度,右边直接截断,方向右到左。 2. 文字拆分为左右两部分(如果末尾有标点,注意书写位置)
 
样式:
.ellipsis-4 { // 限制宽度先 width: 200px; white-space: nowrap; overflow: hidden; .left, .right { display: inline-block; max-width: calc(100% - 5em); min-width: 2.76em; white-space: nowrap; overflow: hidden; } .left { text-overflow: ellipsis; } .right { direction: rtl; width: 5em; } }
 
codepen 在线示例:
 
styled-components原理vitepress组件示例实现