input[type=checkbox] 复选框作为网页中常见的一种组件, 我们在设计开发过程中,为了页面的美观,往往需要设计符合产品的风格样式;
而原生的复选框样式并不美观,且直接修改它的样式,会发现只可以设置少数的样式,其余样式并没有效果。这时,我们就需要自定义checkbox的个性化样式了。
我这里简单的介绍两种CSS实现的方式:
两种方式都使用表单元素中的 label 元素和for属性进行关联,这样当鼠标点击 label 时,会自动选中复选框,这对用户体验更友好;
1、 使用伪类来实现自定义checkbox样式
html布局:
<p>css3改变checkbox默认样式</p>
<div class="checkbox01">
<input type="checkbox" id="checkboxLogin" />
<label for="checkboxLogin">保持登录</label>
</div>
css样式:
.checkbox01 input[type=checkbox] + label::before {
content: "a0";
display: inline-block;
vertical-align: 2px;
width: 14px;
height: 14px;
margin-right: 5px;
border-radius: 3px;
background-color: #261c19;
text-indent: 2px;
line-height: .65;
}
.checkbox01 input[type="checkbox"]:checked + label::before {
content: "2713";
background-color: #f07000;
}
.checkbox01 input[type='checkbox'] {
position: absolute;
clip:rect(0,0,0,0);
}
2、使用图片来替换checkbox的原生样式
html布局:
<p>图片代替 checkbox </p>
<div id="check">
<span>
<input type="checkbox" class="input_check" id="check1" />
<label for="check1"></label>
</span>
<label for="check1">保持登录</label>
</div>
css样式:
#check span { position: relative; }
#check .input_check {
position: absolute;
width: 14px;
height: 14px;
visibility: hidden;
}
#check .input_check+label {
display: inline-block;
width: 14px;
height: 14px;
background: url('./images/checked.png') no-repeat;
background-position: -31px -3px;
background-color: #261c19;
border-radius: 3px;
}
#check .input_check:checked+label {
background-position: 0;
}