纯CSS实现文本Hover与移出时的省略号滑动动画问题
纯CSS实现文本悬停/移开时的省略号滑动动画
需求说明
想要实现鼠标悬停文本时,隐藏的完整内容平滑滑动显示;鼠标移开时,文本重新收缩并显示省略号的动画效果,尝试过animation和transition但未达到预期,需要纯CSS解决方案。
现有尝试代码
p:not(:hover) { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } p:hover { transition: all 100000000s ease-in-out; }
<p> As for when that happeneAnd she is also going to cut back a little on the kind of art that she does. She used to do high - resolution pieces, but now she's mostly doing "modifications," mostly paintings of dogs. She's getting older, she says, and it takes a lot out of her, so she wants to keep that stuff to a minimum. </p>
解决方案
由于text-overflow: ellipsis本身不支持过渡动画,我们可以通过嵌套容器+平移文本的方式模拟滑动效果:
- 外层容器设置固定宽度、禁止换行、溢出隐藏,作为可视区域
- 内层文本容器设为行内块,宽度自适应内容,通过
transform: translateX()控制位置 - 利用
transition实现平移的平滑过渡,hover时让文本回到初始位置显示全部内容,移开时平移到容器边缘并显示省略号
完整代码如下:
.text-container { width: 300px; /* 自定义容器宽度 */ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .text-content { display: inline-block; transition: transform 0.8s ease; } .text-container:hover .text-content { /* 平移距离 = -(文本宽度 - 容器宽度),确保文本刚好填满容器 */ transform: translateX(calc(-100% + 300px)); }
<div class="text-container"> <span class="text-content"> As for when that happenedAnd she is also going to cut back a little on the kind of art that she does. She used to do high-resolution pieces, but now she's mostly doing "modifications," mostly paintings of dogs. She's getting older, she says, and it takes a lot out of her, so she wants to keep that stuff to a minimum. </span> </div>
说明
- 容器宽度需要和
translateX中的数值保持一致,确保hover时文本刚好填满容器 - 调整
transition的时长和缓动函数可控制动画的快慢与流畅度 - 移开鼠标时,文本会自动过渡回初始位置,外层容器的
text-overflow: ellipsis会重新生效
内容的提问来源于stack exchange,提问作者roger
相关产品推荐
相关产品推荐

