css制作单选按钮
使用原生HTML和CSS制作单选按钮
通过原生HTML的<input type="radio">和<label>标签结合CSS自定义样式:
<div class="radio-group">
<input type="radio" id="option1" name="radio-group" checked>
<label for="option1">选项1</label>
<input type="radio" id="option2" name="radio-group">
<label for="option2">选项2</label>
</div>
/* 隐藏原生单选按钮 */
input[type="radio"] {
display: none;
}
/* 自定义样式 */
label {
position: relative;
padding-left: 25px;
cursor: pointer;
}
label:before {
content: "";
position: absolute;
left: 0;
top: 0;
width: 18px;
height: 18px;
border: 2px solid #3498db;
border-radius: 50%;
}
input[type="radio"]:checked + label:before {
background-color: #3498db;
}
input[type="radio"]:checked + label:after {
content: "";
position: absolute;
left: 5px;
top: 5px;
width: 10px;
height: 10px;
border-radius: 50%;
background: white;
}
使用伪元素创建动画效果
为单选按钮添加点击动画:
label:before {
transition: all 0.3s ease;
}
input[type="radio"]:checked + label:before {
transform: scale(1.1);
box-shadow: 0 0 5px rgba(52, 152, 219, 0.5);
}
使用CSS变量实现主题色控制
通过CSS变量使颜色更容易修改:
:root {
--radio-color: #3498db;
}
label:before {
border-color: var(--radio-color);
}
input[type="radio"]:checked + label:before {
background-color: var(--radio-color);
}
响应式设计调整
针对不同屏幕尺寸调整单选按钮大小:
@media (max-width: 768px) {
label:before {
width: 16px;
height: 16px;
}
input[type="radio"]:checked + label:after {
width: 8px;
height: 8px;
}
}
使用Flexbox布局单选按钮组
优化单选按钮组的排列方式:
.radio-group {
display: flex;
gap: 20px;
}
label {
display: flex;
align-items: center;
}
辅助功能优化
确保单选按钮对屏幕阅读器友好:

label {
font-size: 16px;
line-height: 1.5;
color: #333;
}
input[type="radio"]:focus + label:before {
outline: 2px solid #0056b3;
outline-offset: 2px;
}