【CSS3】使用纯CSS做一个简易轮播图(小解送书第二期)

2023-10-17 16:33:08 浏览数 (1)

效果

教学

html

代码语言:javascript复制
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">

    <title>纯CSS实现轮播图效果</title>
    <link rel="stylesheet" href="./lunbo.css">
</head>

<body>
    <div class="swipe">
        <!-- 指示器 -->
        <input type="radio" name="indicator" id="indicator1" checked hidden>
        <label for="indicator1"></label>        
        <input type="radio" name="indicator" id="indicator2" hidden>
        <label for="indicator2"></label>        
        <input type="radio" name="indicator" id="indicator3" hidden>
        <label for="indicator3"></label>

        <ul>
           
            <li>1</li>
            <li>2</li>
            <li>3</li>
        
        </ul>
    </div>
</body>

</html>

css

代码语言:javascript复制
*{
    /* 初始化 */
    margin: 0;
    padding: 0;
}
body{
    /* 100%窗口高度 */
    height: 100vh;
    /* 弹性布局 居中 */
    display: flex;
    justify-content: center;
    align-items: center;
    /* 渐变背景 */
    background: linear-gradient(200deg,#eef1f5,#e6e9f0);
}
.swipe{
    /* 相对定位 */
    position: relative;
    width: 800px;
    height: 500px;
    text-align: center;
    color: #fff;
    /* 溢出隐藏 */
    overflow: hidden;
}
.swipe ul{
    padding: 0;
    width: calc(800px * 3);
    transition: 0.5s;
}
.swipe li{
    float: left;
    width: 800px;
    height: 500px;
    list-style: none;
    line-height: 500px;
    font-size: 50px;
}
.swipe li:nth-child(1){
    background-color: lightcoral;
}
.swipe li:nth-child(2){
    background-color: lightseagreen;
}
.swipe li:nth-child(3){
    background-color: lightsalmon;
}
/* for属性值以“indicator”开头的所有label元素(指示器) */
.swipe label[for^="indicator"]{
    /* 绝对定位 */
    position: absolute;
    top: 450px;
    width: 20px;
    height: 20px;
    background-color: rgba(255,255,255,0.3);
    border-radius: 50%;
    cursor: pointer;
    transition: 0.3s;
}
/* for属性值为“indicator1”的label元素 */
.swipe label[for="indicator1"]{
    left: 44%;
}
/* for属性值为“indicator2”的label元素 */
.swipe label[for="indicator2"]{
    left: 49%;
}
/* for属性值为“indicator3”的label元素 */
.swipe label[for="indicator3"]{
    left: 54%;
}
/* 选中指示器设置ul的margin-left */
#indicator1:checked ~ ul{
    margin-left: 0;
}
#indicator2:checked ~ ul{
    margin-left: -800px;
}
#indicator3:checked ~ ul{
    margin-left: -1600px;
}
/* 选中指示器改变指示器颜色 */
#indicator1:checked ~ label[for="indicator1"]{
    background-color: #fff;
}
#indicator2:checked ~ label[for="indicator2"]{
    background-color: #fff;
}
#indicator3:checked ~ label[for="indicator3"]{
    background-color: #fff;
}

0 人点赞