:checked伪类用于选中状态的复选框或单选按钮,可改变其样式或联动其他元素;通过accent-color可修改默认颜色,结合label与隐藏input能自定义外观,利用兄弟选择器可实现无JS的折叠菜单等交互效果。

当处理复选框的样式时,:checked 伪类选择器非常有用。它能选中处于“选中”状态的单选按钮或复选框,让你可以基于用户交互动态改变样式。
:checked 可用于 input[type="checkbox"] 或 input[type="radio"] 元素,匹配当前被选中的控件。
例如:
input[type="checkbox"]:checked {
accent-color: #4caf50;
}
这段代码会将选中的复选框颜色设为绿色。现代浏览器默认支持 accent-color 属性来简单修改复选框颜色。
立即学习“前端免费学习笔记(深入)”;
如果想完全替换原生复选框外观,通常结合 label 和隐藏的 input 使用。
示例代码:
.custom-checkbox {
display: none;
}
.checkbox-label {
position: relative;
padding-left: 30px;
cursor: pointer;
}
.checkbox-label::before {
content: '';
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 18px;
height: 18px;
border: 2px solid #999;
background-color: white;
}
.checkbox-label::after {
content: '✔';
position: absolute;
left: 4px;
top: 50%;
transform: translateY(-50%);
font-size: 12px;
color: white;
opacity: 0;
}
.custom-checkbox:checked + .checkbox-label::after {
opacity: 1;
}
.custom-checkbox:checked + .checkbox-label::before {
background-color: #4caf50;
border-color: #4caf50;
}
:checked 不仅能改变自身样式,还能控制其他元素的显示,比如制作无 JS 的折叠菜单或开关组件。
利用兄弟选择器(+ 或 ~),可以实现选中后展开内容:
.panel {
display: none;
}
.toggle:checked ~ .panel {
display: block;
}
基本上就这些。使用 :checked 配合 label 和 CSS 生成内容,能做出美观且可访问的复选框样式,无需 JavaScript。关键是结构清晰,确保可点击区域足够大,提升用户体验。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号