修改input checkbox和radio預設樣式
阿新 • • 發佈:2020-08-27
最近專案中遇到一個複選框功能,由於預設的checkbox樣式太醜了,因此需要去掉預設樣式,自定義樣式去美化。
一、html部分
<div class="item"> <input type="checkbox" name="" id="checked_1"> <span></span> <label for="checked_1">應用響應速度太慢</label> </div> <div class="item"> <input type="checkbox" name="" id="checked_2"> <span></span> <label for="checked_2">整體介面設計不美觀</label> </div> <div class="item"> <input type="checkbox" name="" id="checked_3"> <span></span> <label for="checked_3">功能不合理未貼近實戰業務</label> </div>
二、css部分
<style> .item{ position: relative; } .item input[type=checkbox]{ width: 20px; height: 20px; opacity: 0; position: relative; z-index: 2; } span{ width: 20px; height: 20px; background: url(./img/yuan.png) no-repeat; background-size: 100% 100%; position: absolute; top: 0; left: 0; z-index: 1; } label{ font-size: 16px; color: #333; line-height: 20px; position: absolute; } .item input[type=checkbox]:checked + span{ background: url(./img/checked.png) no-repeat; background-size: 100% 100%; } </style>
三、思路
首先,我們需要把checkbox的透明度設定為0:opacity: 0;然後我們需要用到span,作為checkbox的選中狀態顯示。接著給span設定一個背景圖,作為未選中的樣式。通過相鄰選擇器input[type=checkbox]:checked+span給span設定選中時的背景樣式。注意:要設定z-index,input[type=checkbox]要浮在span上面。
最終樣式:
這次筆記就寫到這裡啦!謝謝大家(^_^)。