滚动背景图原理是文字静态透明,background-image通过background-position位移实现滚动;需设置background-size大于容器、no-repeat,并用transparent隐藏文字;横向/竖向滚动需分别配置位移方向与尺寸;动态更新内容时需强制重播动画。
background-image 滚动背景图的核心原理
滚动文字背景图不是让文字动,而是让 background-image 在文字容器内持续位移,靠 background-position 动态变化 + animation 驱动。关键在于:文字本身是静态的、透明的(或半透),真正“滚动”的是它背后的图片。
用 @keyframes 实现平滑横向滚动
横向滚动最常用,比如新闻跑马灯式背景。需注意 background-size 必须大于容器宽度,否则位移无效果;且推荐用 background-repeat: no-repeat 避免拼接感。
示例 CSS:
@keyframes scrollBg {
0% { background-position: 0 0; }
100% { background-position: -200px 0; }
}
.text-scroll {
background-image: url('pattern.png');
background-size: 400px 100%;
background-repeat: no-repeat;
background-position: 0 0;
animation: scrollBg 3s linear infinite;
color: transparent; / 让文字“透出”背景 /
-webkit-text-fill-color: transparent;
}
-
background-size设为两倍以上容器宽,才能看到连续滚动效果 -
color: transparent和-webkit-text-fill-color: transparent缺一不可,否则 Safari 下文字仍显色 - 动画时长(
3s)和位移量(-200px)要匹配,否则出现跳变或卡顿
vertical-direction 滚动常被忽略的兼容性坑
竖向滚动(如弹幕式背景)在 Firefox 和旧版 Chrome 中容易因 background-attachment: fixed 干扰而失效,应避免混用。纯靠 background-position Y 轴变化最稳妥。
立即学习“前端免费学习笔记(深入)”;