CSS动画文本不消失,实现从右侧循环滚动显示的技术需求
解决CSS Marquee动画文本消失问题
原代码的问题在于,动画循环过程中文本会完全移出容器,导致间隙期出现空白。要实现文本即将消失时从右侧重新显示的无缝滚动,可通过以下两种方法解决:
方法一:复制文本元素实现无缝滚动
添加一个相同的文本元素,配合动画延迟,让两个文本块连续滚动,避免空白期。
修改后的HTML:
<div class="wrapper"> <p>Hey, how you're doing? Sorry you can't get through.</p> <p>Hey, how you're doing? Sorry you can't get through.</p> </div>
修改后的CSS:
.wrapper { position: relative; overflow: hidden; height: 25px; width: 100%; border: 1px solid orange; } .wrapper p { position: absolute; margin: 0; line-height: 25px; white-space: nowrap; animation: marquee 5s linear infinite; } /* 第二个文本块初始在容器右侧 */ .wrapper p:nth-child(2) { left: 100%; /* 延迟动画时长的一半,确保两个文本块无缝衔接 */ animation-delay: -2.5s; } @keyframes marquee { 0% { transform: translateX(0); } 100% { transform: translateX(-100%); } }
方法二:使用伪元素生成重复文本(无需额外HTML元素)
利用CSS伪元素生成与原文本相同的内容,紧跟在原文本右侧,实现无缝滚动。
修改后的HTML:
<div class="wrapper"> <p data-text="Hey, how you're doing? Sorry you can't get through.">Hey, how you're doing? Sorry you can't get through.</p> </div>
修改后的CSS:
.wrapper { position: relative; overflow: hidden; height: 25px; width: 100%; border: 1px solid orange; } .wrapper p { position: absolute; margin: 0; line-height: 25px; white-space: nowrap; animation: marquee 5s linear infinite; } /* 用伪元素生成重复文本,紧跟原文本右侧 */ .wrapper p::after { content: attr(data-text); position: absolute; left: 100%; } @keyframes marquee { 0% { transform: translateX(0); } 100% { transform: translateX(-100%); } }
原理说明
原动画中,translateX(100%)和translateX(-100%)是基于文本自身宽度的位移,当文本完全移出容器后,下一次循环启动前会出现空白。上述两种方法通过让两个文本块连续滚动,确保容器内始终有文本显示,实现无缝的滚动效果。
内容的提问来源于stack exchange,提问作者Dinesh Chandra Pandey
相关产品推荐
相关产品推荐

