在页面中咱们常常会使用到 checkbox 和 radio,可是,部分浏览器显示的效果并不能让咱们满意,所以想经过一种方式,更改其样式。
这里使用到的就是使用 label,结合 before 实现样式的更改。
完整代码:css
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>定制checkbox 与 radio</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-size: 1rem; } main { padding: 100px; display: flex; align-items: center; } input[type=checkbox], input[type=radio] { display: none; } input[type=checkbox]+label, input[type=radio]+label { margin-right: 10px; text-align: center; cursor: pointer; display: flex; align-items: center; } input[type=checkbox]+label::before, input[type=radio]+label::before { content: ''; width: 1em; height: 1em; border: 1px solid #ccc; display: inline-block; box-sizing: border-box; padding: 2px; margin-right: 2px; border-radius: 2px; background-color: #fff; } input[type=radio]+label::before { border-radius: 2em; } input[type=checkbox]:checked+label::before, input[type=radio]:checked+label::before { background-color: green; background-clip: content-box; border-color: green; } </style> </head> <body> <main> <input type="checkbox" id="ck_1"> <label for="ck_1">test</label> <input type="checkbox" id="ck_2" checked> <label for="ck_2">test</label> <input type="checkbox" id="ck_3"> <label for="ck_3">test</label> </main> <main> <input type="radio" id="ra_1" name="aaa"> <label for="ra_1">boy</label> <input type="radio" id="ra_2" name="aaa"> <label for="ra_2">girl</label> </main> </body> </html>
效果图:
html
这样相比以前就好看那么一点点,若是引入字体图标,对 css 稍做更改,就能基本知足本身的需求了。浏览器