บทความนี้แนะนำเทคนิคการสร้าง 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>
หลักการทำงาน
- ซ่อน Input จริง -
opacity: 0, height: 0, width: 0แต่ยังคลิกได้ (cursor: pointer) - สร้างกล่องปลอม -
.checkboxMarkedเป็น span วาดเป็นสี่เหลี่ยม - ใช้ Sibling Selector (~) - เมื่อ
input:checkedจะเปลี่ยนสีพื้นหลังและแสดงเครื่องหมายถูก - วาดเครื่องหมายถูก - ใช้
::afterกรอบขาว หมุน 45 องศา (transform: rotate(45deg)) - Hover Effect - เปลี่ยนสีพื้นหลังเมื่อชี้เมาส์
ขยายเป็น Radio Button
ใช้หลักการเดียวกัน แต่เปลี่ยน border-radius: 50% ให้กล่องปลอมเป็นวงกลม และปรับ ::after ให้เป็นจุดกลาง
ผลลัพธ์
Checkbox สีเขียวพร้อมเครื่องหมายถูกสีขาว สวยงาม สอดคล้องกับ Design System ของเว็บไซต์