本文主要介绍了HTML中表单多选框和选项样式化的技巧。首先我们来看看HTML表单中多选框和选项的基本格式:
<form> <p>请选择你喜欢的水果:</p> <input type="checkbox" name="fruit" value="apple" id="apple"> <label for="apple">苹果</label> <input type="checkbox" name="fruit" value="orange" id="orange"> <label for="orange">橘子</label> <input type="checkbox" name="fruit" value="banana" id="banana"> <label for="banana">香蕉</label> </form>
其中,我们使用<input>标签定义多选框,使用<label>标签定义选项名称,并通过for属性与对应的多选框id关联起来。
接下来,我们来看看如何通过CSS样式化这些多选框和选项。
默认情况下,浏览器会呈现一种简单的多选框样式,我们可以通过CSS样式化来美化它们。
首先,我们需要隐藏默认的多选框:
input[type=checkbox] {
display: none;
}然后,我们可以通过:before伪元素来添加自定义的多选框样式:
input[type=checkbox] + label:before {
content: '';
display: inline-block;
width: 20px;
height: 20px;
margin-right: 10px;
border: 1px solid #ccc;
}
input[type=checkbox]:checked + label:before {
background-color: #f00;
}其中,我们使用:before伪元素来添加自定义的多选框样式,使用+选择器来选中对应的label标签,并根据:checked状态来改变样式。
最后,我们需要通过for属性来将label标签与对应的多选框id关联起来:
<input type="checkbox" name="fruit" value="apple" id="apple"> <label for="apple">苹果</label>
除了美化多选框,我们还可以美化选项的样式。
首先,我们需要将默认的选项样式去掉:
input[type=checkbox] + label {
display: inline-block;
margin-right: 10px;
padding-left: 25px;
position: relative;
}
input[type=checkbox] + label:before {
content: '';
display: inline-block;
width: 20px;
height: 20px;
margin-right: 10px;
border: 1px solid #ccc;
position: absolute;
left: 0;
top: 0;
}
input[type=checkbox]:checked + label:before {
background-color: #f00;
}然后,我们可以添加自定义的选项样式:
input[type=checkbox] + label:after {
content: '';
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ccc;
position: absolute;
left: 5px;
top: 5px;
opacity: 0;
transition: opacity .2s;
}
input[type=checkbox]:checked + label:after {
opacity: 1;
}其中,我们使用:after伪元素来添加自定义的选项样式,并使用transition属性来添加渐变效果。
最终,我们可以得到美化后的多选框和选项效果:
本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com
