html代碼結(jié)構(gòu):
<form>
<fieldset class="checkboxes">
<label for="checkbox1"><input type="checkbox" id="checkbox1" name="checkbox">checkbox1</label>
<label for="checkbox2"><input type="checkbox" id="checkbox2" name="checkbox">checkbox2</label>
<label for="checkbox3"><input type="checkbox" id="checkbox3" name="checkbox">checkbox3</label>
</fieldset>
<fieldset class="radios">
<label for="radio1"><input type="radio" id="radio1" name="radiobox">radio1</label>
<label for="radio2"><input type="radio" id="radio2" name="radiobox">radio2</label>
<label for="radio3"><input type="radio" id="radio3" name="radiobox">radio3</label>
</fieldset>
</form>
方法一
- 說(shuō)明:用屬性
appearance
刪除<input>
的默認(rèn)樣式聪舒,并用雪碧圖作為背景完成自定義樣式。
兼容性較差虐急,不支持IE瀏覽器箱残,在FireFox瀏覽器中無(wú)法正常顯示,可在Chrome和Edge中正常顯示止吁。 - 主要CSS代碼:
/*刪除控件默認(rèn)樣式*/
input[type="checkbox"], input[type="radio"] {
-webkit-appearance: none;
-moz-appearance: none;
-ms-appearance: none;
appearance: none;
}
/*使用雪碧圖添加背景*/
input[type="checkbox"] {
width: 16px;
height: 16px;
background-image: url(img/1.png);
background-position: 0 16px;
}
input[type="checkbox"]:checked {
background-position: 16px 16px;
}
input[type="radio"] {
width: 16px;
height: 16px;
background-image: url(img/1.png);
background-position: 0 0;
}
input[type="radio"]:checked {
background-position:16px 0;
}
方法二
- 說(shuō)明:先使用
display:none;
將<input>
的默認(rèn)樣式隱藏被辑,再使用偽元素::before
插入<label>
為checkbox與radio設(shè)置樣式(此處使用雪碧圖做背景)。
兼容性較好敬惦,但不支持IE8及以下盼理。 - 主要css代碼:
/*隱藏input默認(rèn)樣式*/
input[type="checkbox"], input[type="radio"] {
display: none;
}
/*使用雪碧圖添加背景*/
/*注意使用偽元素::before*/
.checkboxes label::before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
margin-right: 5px;
background-image: url(img/1.png);
background-position: 0 16px;
vertical-align: bottom;
}
input[type="checkbox"]:checked+label::before {
background-position: 16px 16px;
}
.radios label::before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
margin-right: 5px;
background-image: url(img/1.png);
background-position: 0 0;
vertical-align: bottom;
}
input[type="radio"]:checked+label::before {
background-position: 16px 0;
}