본문 바로가기
HTML/CSS

[HTML/CSS] 체크박스 토글 버튼 만들기

by teamnova 2022. 7. 11.
728x90

안녕하세요.

오늘은 toggle 버튼을 한번 만들어보도록 하겠습니다.

 

소스코드

index.html

<!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>토글버튼</title>
    <link rel="stylesheet" href="./toggle_btn.css">
</head>
<body>

  <!-- 토글 -->
  <div class="toggle_box">
    <input type="checkbox" id="custom_input"></input>
    <label for="custom_input" class="toggle_btn_label">
      <span></span>
    </label>
  </div>

</body>
</html>

 

toggle_btn.css

/* 멘토링 상태변경 토글 */
/* 멘토 상태변경 토글 */
.toggle_box {
    display: flex;
    align-items: center;
    z-index: -1;
    margin-top: 20px;
}

#custom_input {
    display: none;
}

#custom_input + label.toggle_btn_label {
    position: relative;
    width: 12rem;
    height: 3rem;
}

#custom_input + label.toggle_btn_label > span {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-radius: 40px;
    background-color: #ccc;
    
    transition: all .4s;

}

#custom_input + label.toggle_btn_label > span:before {
    display: flex;
    position: absolute;
    height: 2.5rem;
    width: fit-content;
    padding: 0 1rem;
    left: 0.25rem;
    bottom: 0.25rem;
    border-radius: 20px;
    background-color: #fff;
    
    content: "초기값";
    align-items: center;
    font-weight: bold;
    color: rgb(29, 29, 29);

    -webkit-transition: all .4s;
    transition: all .4s;
}

#custom_input:checked + label.toggle_btn_label > span {
    background-color: black;
}

#custom_input:checked + label.toggle_btn_label > span:before {
    -webkit-transform: translateX(calc(11.5rem - 100%));
    -ms-transform: translateX(calc(11.5rem - 100%));
    transform: translateX(calc(11.5rem - 100%));
    right: 0.25rem;
    bottom: 0.25rem;
    content: "변경값";
}

#custom_input:disabled + label.toggle_btn_label {
    display: none;
}

 

시현 영상