今天和大家分享一个使用纯 CSS 实现的无限轮播效果。这个轮播效果不需要任何 JavaScript,完全依靠 CSS 动画来实现,而且支持鼠标悬停暂停。
效果展示
实现原理
实现这个效果的核心在于:
- 创建两组完全相同的内容
- 使用 CSS animation 让内容持续向左滚动
- 当第一组内容完全滚出视野时,第二组内容刚好补上,造成无缝衔接的效果
代码实现
首先是 HTML 结构:
<div class="carousel">
<div class="group">
<div class="card">A</div>
<div class="card">B</div>
<div class="card">C</div>
</div>
<!-- 复制一组相同的内容 -->
<div class="group" aria-hidden="true">
<div class="card">A</div>
<div class="card">B</div>
<div class="card">C</div>
</div>
</div>
CSS 样式:
.carousel {
margin: 0 auto;
padding: 20px 0;
max-width: 700px;
overflow: hidden;
display: flex;
> * {
flex: 0 0 100%;
}
&:hover .group {
animation-play-state: paused;
cursor: pointer;
}
}
.card {
width: 100%;
color: #000;
border-radius: 24px;
box-shadow: rgba(0, 0, 0, 10%) 5px 5px 20px 0;
padding: 20px;
font-size: xx-large;
justify-content: center;
align-items: center;
min-height: 200px;
&:nth-child(1) { background: #7958ff; }
&:nth-child(2) { background: #7bb265; }
&:nth-child(3) { background: #d29b9b; }
}
.group {
display: flex;
gap: 20px;
padding-right: 20px;
will-change: transform;
animation: scrolling 10s linear infinite;
}
@keyframes scrolling {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-100%);
}
}
关键点解析
- 容器设置
- 使用
overflow: hidden
隐藏超出部分 - 使用
display: flex
让两组内容水平排列
- 使用
- 动画实现
- 使用
@keyframes
定义动画,从 0% 位置移动到 -100% 位置 - 设置
animation: scrolling 10s linear infinite
使动画无限循环 linear
确保动画速度均匀
- 使用
- 性能优化
- 使用
will-change: transform
提前告知浏览器即将发生变换 - 使用
transform
而不是改变left
或margin
属性,可以获得更好的性能
- 使用
- 交互体验
- 当鼠标悬停时,设置
animation-play-state: paused
暂停动画 - 添加
cursor: pointer
提示用户可交互
- 当鼠标悬停时,设置
- 无障碍优化
- 为第二组重复内容添加
aria-hidden="true"
,避免屏幕阅读器重复读取
- 为第二组重复内容添加
使用场景
这种无限轮播效果适用于:
- 展示产品特性
- 显示用户评价
- 展示合作伙伴 logo
- 新闻标题滚动等
注意事项
- 动画时长需要根据内容长度和期望的滚动速度来调整
- 内容数量不宜过多,否则会影响性能
- 在移动端需要注意性能问题
- 建议添加媒体查询,在小屏幕设备上调整合适的显示方式
总结
这个纯 CSS 实现的无限轮播效果,代码简洁,性能良好,而且不需要依赖任何 JavaScript 库。通过合理运用 CSS 动画和变换,我们可以实现很多有趣的效果。希望这个例子能给大家一些启发!