input+css写一个开关按钮

137 阅读1分钟

需求

纯html+css写一个开关按钮如下

checkbox.gif

使用技术

伪元素选择器+伪类选择器

实现思路

使用input元素,重写input元素样式,使用伪元素画按钮滑动样式

代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        body {
            width: 100%;
            height: 100vh;
            display: flex;
        }
        .my_checkbox {
            display: block;
            width: 200px;
            height: 80px;
            margin: auto;
            -webkit-appearance: none;
            -moz-appearance: none;
            outline: none;
            border: 5px solid #888;
            border-radius: 40px;
            background: linear-gradient(to bottom, #5b5b5b, #f0f0f0);
            box-shadow: 0 0 20px #888, inset 5px -5px 30px #333;
            position: relative;
            transition: 0.5s;
        }
        .my_checkbox::before {
            display: block;
            width: 120px;
            height: 60px;
            content: '';
            background: linear-gradient(to top, #000, #6b6b6b);
            border: 5px solid #555;
            border-radius: 35px;
            position: absolute;
            top: 0;
            left: 0;
            transition: 0.5s;
        }
        .my_checkbox::after {
            display: block;
            width: 10px;
            height: 10px;
            content: '';
            background-color: darkgray;
            border-radius: 50%;
            position: absolute;
            top: 50%;
            margin-top: -5px;
            left: 90px;
            transition: 0.5s;
        }
        /*复选框被选中后的样式*/
        .my_checkbox:checked::before {
            left: 60px;
            box-shadow: 0 0 15px skyblue;
        }
        .my_checkbox:checked::after {
            left: 150px;
            background-color: aqua;
            box-shadow: 0 0 15px skyblue;
        }
        .my_checkbox:checked {
            border: 5px solid skyblue;
            background: linear-gradient(to bottom, #00aeae, aqua);
        }
    </style>
</head>
<body>
<input type="checkbox" class="my_checkbox">
</body>
</html>