将html的radio单选框自定义样式为正方形和对号
背景:
如何能把html的
<input type="radio" name="option">
改成自定义的样式呢?比如想要把他变成正方形,选中的时候是对号。默认的样式太丑了
默认样式:
自定义样式:
实现代码
<!DOCTYPE html>
<html>
<head>
<style>
input[type="radio"] {
display: none;
}
.square-radio {
display: flex;
position: relative;
width: 20px;
height: 20px;
border: 2px solid #333;
cursor: pointer;
}
.square-radio::after {
content: "✓";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 14px;
color: #333;
display: none;
}
input[type="radio"]:checked + .square-radio::after {
color: #2196F3;
display: block;
}
</style>
</head>
<body>
<div class="box">
性别:
<label>
男
<input type="radio" name="option">
<span class="square-radio"></span>
</label>
<label>
女
<input type="radio" name="option">
<span class="square-radio"></span>
</label>
</div>
</body>
</html>