因爲原生的checkbox樣式比較難看,因此咱們常常須要改寫它的樣式,美化複選框,因此今天總結下自定義checkbox樣式的方法,上代碼:css
html文件html
<label class="checkbox-inline"> <input type="checkbox" class="checkbox" name="hobby"> <span class="hobby">羽毛球</span> <span class="checkmark"></span> </label> <label class="checkbox-inline"> <input type="checkbox" class="checkbox" name="hobby"> <span class="hobby">跑步</span> <span class="checkmark"></span> </label>
csscss3
.checkbox-inline{ position: relative; } .checkbox{ position: absolute; width: 0; height: 0; } .checkmark{ position: absolute; top: 2px; left: 0; height: 15px; width: 15px; border: 1px solid; background-color: #fff; border-radius: 10px; } .hobby{ padding-left: 20px; } .checkbox-inline input:checked ~ .checkmark { background-color: #492c94; } .checkbox-inline input:checked ~ .checkmark:after { display: block; } .checkbox-inline .checkmark:after { display: none; content: ""; position: absolute; left: 4px; top: 0; width: 4px; height: 10px; border: solid white; border-width: 0 2px 2px 0; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); }
效果圖(未選中與選中對比):web
採起的作法是spa
這裏還涉及到一個知識點,僞元素屬於主元素的一部分,所以點擊僞元素觸發的是主元素的click事件。code