input单选框和复选框改变自带的颜色和背景色
warning:
这篇文章距离上次修改已过262天,其中的内容可能已经有所变动。
在CSS中,可以通过设置::before
伪元素的background-color
属性来改变单选框和复选框的颜色。同时,由于这些元素是浏览器自带的,你不能直接改变它们的颜色,因此需要隐藏原生的单选框和复选框,然后使用标准的HTML元素和:checked
伪类来创建自定义的样式。
以下是一个示例,演示如何自定义单选框和复选框的颜色和背景色:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Checkbox and Radio Buttons</title>
<style>
/* 隐藏原生单选框和复选框 */
.radio-input, .checkbox-input {
display: none;
}
/* 自定义单选框样式 */
.radio-label {
display: inline-block;
padding-left: 25px;
position: relative;
cursor: pointer;
user-select: none;
}
.radio-label:before {
content: '';
width: 15px;
height: 15px;
border-radius: 50%;
position: absolute;
left: 0;
top: 0;
background-color: #fff; /* 背景色 */
border: 2px solid #777; /* 边框色 */
}
.radio-input:checked + .radio-label:before {
content: '';
width: 15px;
height: 15px;
border-radius: 50%;
position: absolute;
left: 0;
top: 0;
background-color: blue; /* 选中时的背景色 */
border: 2px solid blue; /* 选中时的边框色 */
}
/* 自定义复选框样式 */
.checkbox-label {
display: inline-block;
padding-left: 25px;
position: relative;
cursor: pointer;
user-select: none;
}
.checkbox-label:before {
content: '';
width: 15px;
height: 15px;
position: absolute;
left: 0;
top: 0;
background-color: #fff; /* 背景色 */
}
.checkbox-input:checked + .checkbox-label:before {
content: '✔';
width: 15px;
height: 15px;
position: absolute;
left: 0;
top: 0;
background-color: green; /* 选中时的背景色 */
color: white; /* 选中时的文字颜色 */
text-align: center;
}
</style>
</head>
<body>
<form>
<!-- 单选框 -->
<input type="radio" id="option1" name="radio-group" class="radio-input">
<label for="option1" class="radio-label"></label>
<label for="option1">Option 1</label>
<input type="radio" id="option2" name="radio-group" class="
评论已关闭