CSS3中的RadioButton(单选框)和CheckBox(复选框)都是Web上最常见的页面元素,用于收集和处理用户的输入。用CSS3样式来美化我们的页面元素是非常不错的选择,这可以帮助增加用户交互的体验,使得网页看起来更简洁、时尚。在这篇文章中,我们将介绍如何使用CSS3来给RadioButton和CheckBox增加一些样式。
input[type=radio],input[type=checkBox] { /* 将默认的圆形隐藏掉 */ display: none; } input[type=radio] + label,input[type=checkBox] + label { /* 为RadioButton和CheckBox前面的label标签设置样式 */ display: inline-block; cursor: pointer; height: 20px; line-height: 20px; padding-left: 20px; position: relative; margin-right: 10px; } input[type=radio] + label:before,input[type=checkBox] + label:before { /* 新建伪元素通过content属性来识别使用哪种样式,让文字跟着样式一起改变 */ content: ''; display: inline-block; width: 16px; height: 16px; margin-right: 10px; position: absolute; left: 0; bottom: 1px; background-color: #fff; /* 不变的白色背景 */ border-radius: 50%; /* 需要圆角 */ border: 1px solid #777777; /* 边框 */ } input[type=radio]:checked + label:before,input[type=checkBox]:checked + label:before { /* 为选中的RadioButton和CheckBox设置特定的样式 */ content: '\2713'; color: #fff; background-color: #777777; text-align: center; }
RadioButton和CheckBox的HTML和CSS都是类似的,我们再次重申要使用label标签,因为它可以关联输入和标签值。在CSS中,我们处理默认情况下的RadioButton和CheckBox样式的方法与以前的技术基本相似:通过"display:none"来制作自定义的RadioButton和CheckBox。
当我们进行新的美化时,我们将用一个16*16像素的白色圆形来代替默认的RadioButton和CheckBox。这个New Element会在被选中的时候填充,使它看起来与RadioButton或CheckBox在一起工作。当Checked时,为RadioButton和CheckBox设置与文本一致的颜色、白底的新样式。这样我们就完成了RadioButton和CheckBox的美化。