纯CSS实现超级简单的轮播图
实现要点
- 需要一个父容器包裹轮播卡片
- 父元素需不能是static定位(默认定位)
- 父元素需设置overflow属性
- 轮播卡片需要相对于父元素进行绝对定位
- 轮播卡片需要进行偏移100%的倍数
- 动画使用transform属性进行位置偏移
效果
源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Carousel</title>
</head>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
padding-top: 100px
}
.carousel-wrap {
position: relative;
width: 400px;
height: 200px;
background-color: antiquewhite;
overflow: hidden;
}
.box {
position: absolute;
width: 100%;
height: 100%;
background-color: blueviolet;
animation: box 20s infinite ease-out;
display: flex;
justify-content: center;
align-items: center
}
@keyframes box {
0% {
transform: translateX(0%);
}
10%,
20% {
transform: translateX(-100%);
}
30%,
40% {
transform: translateX(-200%);
}
50%,
60% {
transform: translateX(-300%);
}
70%,
80% {
transform: translateX(-400%);
}
90%,
100% {
transform: translateX(-500%);
}
}
.box:nth-child(1) {
background-color: violet;
left: 100%
}
.box:nth-child(2) {
background-color: aqua;
left: 200%
}
.box:nth-child(3) {
background-color: turquoise;
left: 300%
}
.box:nth-child(4) {
background-color: tomato;
left: 400%;
}
.box:nth-child(5) {
background-color: chartreuse;
left: 500%
}
</style>
<body>
<div class="carousel-wrap">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
</div>
</body>
</html>