如何修改美化radio、checkbox的默认样式?

106 阅读1分钟

"```markdown

修改美化radio、checkbox的默认样式

使用CSS样式自定义radio和checkbox的外观

通过以下CSS样式可以修改美化radio和checkbox的默认样式:

/* 隐藏原始的radio和checkbox */
input[type=radio],
input[type=checkbox] {
    display: none;
}

/* 自定义radio样式 */
.custom-radio {
    display: inline-block;
    width: 20px;
    height: 20px;
    border-radius: 50%; /* 圆形 */
    border: 2px solid #999;
    position: relative;
    cursor: pointer;
}

/* 选中状态的自定义radio样式 */
.custom-radio::after {
    content: '';
    display: block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #999;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    opacity: 0; /* 默认不显示 */
}

/* 当radio选中时显示内部小圆点 */
input[type=radio]:checked + .custom-radio::after {
    opacity: 1;
}

/* 自定义checkbox样式 */
.custom-checkbox {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 2px solid #999;
    position: relative;
    cursor: pointer;
}

/* 选中状态的自定义checkbox样式 */
.custom-checkbox::after {
    content: '';
    display: block;
    width: 14px;
    height: 5px;
    border-bottom: 2px solid #fff;
    border-right: 2px solid #fff;
    transform: rotate(-45deg);
    position: absolute;
    top: 2px;
    left: 5px;
    opacity: 0; /* 默认不显示 */
}

/* 当checkbox选中时显示对号 */
input[type=checkbox]:checked + .custom-checkbox::after {
    opacity: 1;
}

HTML示例

使用上述自定义样式时,HTML结构可以这样写:

<input type=\"radio\" id=\"radio1\" name=\"radio-group\" class=\"hidden-radio\">
<label for=\"radio1\" class=\"custom-radio\"></label>
<input type=\"checkbox\" id=\"checkbox1\" class=\"hidden-checkbox\">
<label for=\"checkbox1\" class=\"custom-checkbox\"></label>

通过这些CSS和HTML结构,可以轻松地修改美化radio和checkbox的默认样式,使其更符合设计需求,并提升用户体验。