通过 css `:has()` 选择器可精准定位包含已勾选 radio 的父容器,从而为整个 `.form-check` 区域添加边框;配合伪元素优化按钮视觉表现,并利用兄弟选择器微调标签间距,实现按钮与标签一体化高亮效果。
在表单交互设计中,常需对用户已选中的单选按钮()及其关联标签(
CSS :has() 是一个父选择器,允许我们根据子元素状态反向选中其祖先元素。这是实现本需求最简洁、语义最清晰的方式:
.form-check:has(> input[type="radio"]:checked) {
display: inline-flex;
align-items: center;
padding: 10px 20px;
border: 2px solid #dc3545;
border-radius: 8px;
background-color: #fff9f9;
}✅ 优点:
⚠️ 注意::has() 已被 Chrome 105+、Firefox 103+、Safari 15.4+ 原生支持(Can I use :has())。若需兼容旧版 IE 或较老浏览器,需降级方案(见文末补充)。

为提升视觉一致性,可隐藏原生 radio 并用伪元素重绘,同时确保 label 与自定义控件对齐:
/* 隐藏原生 radio */
.form-check input[type="radio"] {
position: absolute;
opacity: 0;
pointer-events: none;
}
/* 自定义 radio 圆点(未选中) */
.form-check input[type="radio"] + label::before {
content: '';
display: inline-block;
width: 18px;
height: 18px;
border: 2px solid #6c757d;
border-radius: 50%;
margin-right: 8px;
vertical-align: middle;
}
/* 选中时的圆点填充 */
.form-check input[type="radio"]:checked + label::before {
background-color: #dc3545;
border-color: #dc3545;
}
/* 选中时 label 文字加粗 & 微调间距 */
.form-check input[type="radio"]:checked + label {
font-weight: 600;
color: #212529;
}配合 HTML(保持 for/id 关联):
No
.form-check.checked { border: 2px solid #dc3545; border-radius: 8px; }综上,借助现代 CSS 的 :has() 能力,我们能以声明式、轻量、可维护的方式,优雅地实现“单选按钮与其标签整体高亮”的交互效果,兼顾语义、可访问性与开发效率。
来电咨询