利用僞元素before實現自定義checkbox樣式

 原理:label標籤的for屬性可以將文字與複選框進行關聯,點擊文字可以同時將複選框選中。 隱藏checkbox標籤,利用label標籤的before僞元素來實現自定義樣式。設置before僞元素的邊框border屬性實現複選框的外框,before僞元素的content值可爲unicode字符集,這樣就可以設置checkbox中選中狀態,可以實現勾選效果、五角星效果、多邊形效果等等

代碼:

<html>
    <head>
        <style>
            * { font-size: 12px; }
            input[type=checkbox].chk1 { display: none; }
            input[type=checkbox].chk1 + label::before { content: ""; display: inline-block; width: 10px; height: 10px; line-height: 10px; border: 1px solid #000; vertical-align: text-bottom; }
            input[type=checkbox].chk1:checked + label::before { content: "\2713"; width: 10px; height: 10px; line-height: 10px; }            
            
            input[type=checkbox].chk2 { display: none; }
            input[type=checkbox].chk2 + label::before { content: ""; display: inline-block; width: 10px; height: 10px; line-height: 10px; border: 1px solid #000; margin-right: 3px; vertical-align: text-bottom; }
            input[type=checkbox].chk2:checked + label::before { content: "\2713"; width: 10px; height: 10px; line-height: 10px; text-indent: 1px; }        
            
            input[type=checkbox].chk3 { display: none; }
            input[type=checkbox].chk3 + label::before { content: ""; display: inline-block; width: 10px; height: 10px; line-height: 10px; border: 1px solid #000; margin-right: 3px; vertical-align: text-bottom; }
            input[type=checkbox].chk3:checked + label::before { content: "\25c6"; width: 10px; height: 10px; line-height: 10px; }
        </style>
    </head>
    <body>
        <div>
            <input type="checkbox" id="chk1" class="chk1" />
            <label for="chk1"></label>
        </div>
        <br />
        <br />
        <div>
            <input type="checkbox" id="chk2" class="chk2" />
            <label for="chk2">選中</label>
        </div>
        <br />
        <br />
        <div>
            <input type="checkbox" id="chk3" class="chk3" />
            <label for="chk3">選中</label>
        </div>
    </body>
</html>

 

效果圖:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章