利用css3修改input[type=radio]樣式

利用css3修改input[type=radio]樣式

作項目的時候須要使用單選按鈕input[type=radio],可是默認的樣式與UI設計不一致,因此須要修改默認的樣式,以下圖。搜索的時候發現有一些實現是利用背景圖實現。不想使用圖片,因此利用css3的從新實現了一遍。在ie8下無效。css

圖片描述

原理

利用<label>標籤與對應的<input>關聯,給<input>設置透明,使用position(定位)讓用戶看到的是<label>標籤的樣式,點擊<label>時會選擇到對應的<input>,使用<input>:checked僞類選擇器來改變選中<label>的樣式.html

實現代碼

html
<form>
    <div>
        <input id="item1" type="radio" name="item" value="選項一" checked>
        <label for="item1"></label>
        <span>選項一</span>
    </div>
    <div>
        <input id="item2" type="radio" name="item" value="選項二">
        <label for="item2"></label>
        <span>選項二</span>
    </div>
</form>

css

div {
            position: relative;
            line-height: 30px;
        }
        
        input[type="radio"] {
            width: 20px;
            height: 20px;
            opacity: 0;
        }
        
        label {
            position: absolute;
            left: 5px;
            top: 3px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            border: 1px solid #999;
        }
        
        /*設置選中的input的樣式*/
        /* + 是兄弟選擇器,獲取選中後的label元素*/
        input:checked+label { 
            background-color: #fe6d32;
            border: 1px solid #fe6d32;
        }
        
        input:checked+label::after {
            position: absolute;
            content: "";
            width: 5px;
            height: 10px;
            top: 3px;
            left: 6px;
            border: 2px solid #fff;
            border-top: none;
            border-left: none;
            transform: rotate(45deg)
        }

dome

連接:http://runjs.cn/code/hmevb9gscss3

相關文章
相關標籤/搜索