CSS 实现⾃定义样式的单选框与多选框
前端在开发的过程中,经常会遇见使⽤单选框以及多选框的情况,但是默认的选框按钮的样式单⼀,⼀般我们需要去⾃定义⼀些选框按钮的样式;
通常情况下,单选、多选为⽅便⾃定义样式,⼀般会采⽤input+label去实现,这⾥实现的原理主要是运⽤了label标签的for属性;
for 属性规定 label 与哪个表单元素绑定。
1. 单选框
实现⽅式:input type=radio + label
HTML:CSS:
<body>
<div class ="box">
<input type="radio" id ="radio1" name ="radio" checked="checked"/><label for ="radio1">选项⼀</label>
</div >
<div class ="line"></div >
<div class ="box">
<input type="radio" id ="radio2" name ="radio"/><label for ="radio2">选项⼆</label>
</div >
<div class ="line"></div >
<div class ="box">
<input type="radio" id ="radio3" name ="radio"/><label for ="radio3">选项三</label>
</div >
<div class ="line"></div >
<div class ="box">
<input type="radio" id ="radio4" name ="radio"/><label for ="radio4">选项四</label>
</div >
<div class ="line"></div >
<div class ="box">
<input type="radio" id ="radio5" name ="radio"/><label for ="radio5">选项五</label>
borderbox</div >
<div class ="line"></div >
</body>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
border: none;
box-sizing: border-box; outline: none;
}
.box{
width: 100%;
height: 50px;
text-align: center;
}
input{
display: none;
}
label{
width: 100%;
height: 100%;
display: inline-block;
position: relative;
line-height: 50px;
color:#999;
}
label:active{
background:#EEEEEE; }
label:after{
content: "";/*必须设置*/ display: inline-block;
width: 20px;
height: 20px;
border: 1px solid green; position: absolute;
top: 15px;
left: 15px;
border-radius: 20px;
}
input:checked+label:after{ background-color: green; }
.line{
width: 100%;
height: 1px;
background:#ccc;
opacity: 0.2;
}
</style>
2. 多选框
实现⽅式:input type=checkbox + label
HTML:css:
<body>
<div class ="box">
<input type="checkbox" id ="checkbox1"/><label for ="checkbox1">选项⼀</label> </div >
<div class ="line"></div >
<div class ="box">
<input type="checkbox" id ="checkbox2"/><label for ="checkbox2">选项⼆</label> </div >
<div class ="line"></div >
<div class ="box">
<input type="checkbox" id ="checkbox3"/><label for ="checkbox3">选项三</label> </div >
<div class ="line"></div >
<div class ="box">
<input type="checkbox" id ="checkbox4"/><label for ="checkbox4">选项四</label> </div >
<div class ="line"></div >
<div class ="box">
<input type="checkbox" id ="checkbox5"/><label for ="checkbox5">选项五</label> </div >
<div class ="line"></div >
</body>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
border: none;
box-sizing: border-box; outline: none;
}
.box{
width: 100%;
height: 50px;
}
input{
display: none;
}
label{
width: 100%;
height: 50px;
display: inline-block;
line-height: 50px;
position: relative;
text-align: center;
}
label:active{
background:#EEEEEE; }
label:after{
content: "";
width: 20px;
height: 20px;
border: 1px solid green; border-radius: 20px;
display: inline-block;
position: absolute;
top: 15px;
left: 15px;
}
input:checked+label:after{ background-color: green; }
.line{
width: 100%;
height: 1px;
background:#CCCCCC; opacity: 0.3;
}
</style>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论