Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

วิธีสร้าง Checkbox และ Radio Button แบบกำหนดเอง (Custom) ด้วย CSS

บทความนี้แนะนำเทคนิคการสร้าง Checkbox และ Radio Button ที่ปรับแต่งรูปลักษณ์ได้ตามต้องการ โดยซ่อน Input ต้นฉบับและใช้ Pseudo-element (::after) วาดเครื่องหมายแทน

ตัวอย่างโค้ด (Checkbox)

<!DOCTYPE html> <html> <style> .checkboxContainer {    display: block;    position: relative;    padding-left: 35px;    margin-bottom: 12px;    cursor: pointer;    font-size: 22px;    user-select: none; } .checkboxContainer input {    position: absolute;    opacity: 0;    cursor: pointer;    height: 0;    width: 0; } .checkboxMarked {    position: absolute;    top: 0;    left: 0;    height: 25px;    width: 25px;    background-color: #eee; } .checkboxContainer:hover input ~ .checkboxMarked {    background-color: rgb(205, 255, 199); } .checkboxContainer input:checked ~ .checkboxMarked {    background-color: rgb(5, 170, 32); } .checkboxMarked:after {    content: "";    position: absolute;    display: none; } .checkboxContainer input:checked ~ .checkboxMarked:after {    display: block; } .checkboxContainer .checkboxMarked:after {    left: 9px;    top: 5px;    width: 5px;    height: 10px;    border: solid white;    border-width: 0 3px 3px 0;    transform: rotate(45deg); } </style> <body> <h1>Custom Checkbox Example</h1> <label class="checkboxContainer">Rice    <input type="checkbox" checked="checked">    <span class="checkboxMarked"></span> </label> <label class="checkboxContainer">Flour    <input type="checkbox">    <span class="checkboxMarked"></span> </label> </body> </html>

หลักการทำงาน

  1. ซ่อน Input จริง - opacity: 0, height: 0, width: 0 แต่ยังคลิกได้ (cursor: pointer)
  2. สร้างกล่องปลอม - .checkboxMarked เป็น span วาดเป็นสี่เหลี่ยม
  3. ใช้ Sibling Selector (~) - เมื่อ input:checked จะเปลี่ยนสีพื้นหลังและแสดงเครื่องหมายถูก
  4. วาดเครื่องหมายถูก - ใช้ ::after กรอบขาว หมุน 45 องศา (transform: rotate(45deg))
  5. Hover Effect - เปลี่ยนสีพื้นหลังเมื่อชี้เมาส์

ขยายเป็น Radio Button

ใช้หลักการเดียวกัน แต่เปลี่ยน border-radius: 50% ให้กล่องปลอมเป็นวงกลม และปรับ ::after ให้เป็นจุดกลาง

ผลลัพธ์

Checkbox สีเขียวพร้อมเครื่องหมายถูกสีขาว สวยงาม สอดคล้องกับ Design System ของเว็บไซต์