在頁面中咱們常常會使用到 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 稍做更改,就能基本知足本身的需求了。瀏覽器