轮播图实现方式有很多,在工作中基本上都是使用js或者组件去完成了,但是CSS也可以做出轮播图,使用CSS的过渡效果(transition)和动画定义(keyframes),以及动画的调(animation)。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS轮播图</title>
<style>
/* 通配符清除默认样式 */
* {
/* 清除内外边距 */
margin: 0;
padding: 0;
/* 字体不加粗 */
font-weight: normal;
/* 去除下划线 */
text-decoration: none;
/* 去除无序列表li标签的小圆点 */
list-style: none;
}
body {
/* 设置背景 */
background-color: #66CCFF;
}
.box {
position: absolute;
/* 让整个盒子居中 */
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 960px;
height: 540px;
/* 溢出隐藏 */
overflow: hidden;
}
.list {
position: absolute;
top: 0;
left: 0;
/* 设置ul更大的宽度,让子元素li可以并排浮动 */
width: 4800px;
height: 540px;
}
.list li {
/* 让每一个li标签并排浮动 */
float: left;
width: 960px;
height: 540px;
/* 使用animation标签,设置动画名称 时间 循环次数(此处为无限循环) 匀速 */
animation: move 13s infinite linear;
}
/* 定义动画 */
@keyframes move {
/* 0的时候显示第五张 */
0% {
transform: translateX(0px);
}
11% {
transform: translateX(-960px);
}
/* 设置同样的值让图片停留一会 */
22% {
transform: translateX(-960px);
}
44% {
transform: translateX(-1920px);
}
55% {
transform: translateX(-1920px);
}
66% {
transform: translateX(-2880px);
}
77% {
transform: translateX(-2880px);
}
88% {
transform: translateX(-3870px);
}
100% {
transform: translateX(-3870px);
}
}
/* 高级选择器选择每一张图片的地址 */
.list li:nth-child(1) {
background: url("") no-repeat center/cover;
}
.list li:nth-child(2) {
background: url("") no-repeat center/cover;
}
.list li:nth-child(3) {
background: url("") no-repeat center/cover;
}
.list li:nth-child(4) {
background: url("") no-repeat center/cover;
}
.list li:nth-child(5) {
background: url("") no-repeat center/cover;
}
</style>
</head>
<body>
<div class="box">
<ul class="list">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
</html>