CSS實現開關特效

Yannick Li發表於2020-10-03

在這裡插入圖片描述
點選後
在這裡插入圖片描述

index.css:

*{
    margin: 0;
    padding: 0;
}
body{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}
label{
    transform: scale(2);
    width: 100px;
    height: 50px;
    border: solid 1px #ddd;
    background: #ddd;
    border-radius: 25px;
    position: relative;
    overflow: hidden;
}
label input{
    visibility: hidden;
}
label input::after{
    visibility: visible;
    content: '';
    width: 40px;
    height: 40px;
    position: absolute;
    left: 0;
    top: 0;
    background: #fff;
    border-radius: 50%;
    left: 5px;
    top: 5px;
    transition: all 0.2s;
}
label input:checked::after{
    transform: translateX(50px);
}
/* 關於背景顏色變化 */
label input::before{
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    visibility: visible;
    transition: all 0.2s;
}
label input:checked::before{
    background: rgb(70, 175, 93);
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="index.css">
    <title>Document</title>
</head>
<body>
    <label>
        <input type="checkbox" class="checked">
    </label>
</body>
</html>

相關文章