如何为固定HTML结构的Toggle开关添加勾选和叉号CSS样式?
适配自定义HTML结构的带勾选/叉号Toggle开关CSS方案
我需要仅通过CSS将标准toggle开关修改为带勾选和叉号的样式,现有示例代码无法适配我的固定HTML结构,我的HTML代码如下:
<div class="my-tgl"> <input type="checkbox" id="my-group-id-Targt"> <label class="my-switch" for="my-group-id-Targt"> <span class="my-switch-nob" role="switch"></span> </label> </div>
以下是适配该结构的CSS方案,完全实现目标样式效果:
*, *::before, *::after { transition: 400ms all ease-in-out 50ms; box-sizing: border-box; backface-visibility: hidden; } /* 隐藏原生复选框 */ .my-tgl input[type="checkbox"] { display: none; } /* 开关容器(未选中状态) */ .my-tgl .my-switch { display: block; height: 26px; width: 42px; background: rgba(224, 224, 224, 1); border-radius: 9999px; position: relative; cursor: pointer; } /* 开关滑块(未选中状态) */ .my-tgl .my-switch-nob { height: 22px; width: 22px; background: rgba(255, 255, 255, 1); border-radius: 9999px; position: absolute; top: 2px; left: 2px; transition: inherit; } /* 未选中时的叉号样式 */ .my-switch-nob::before, .my-switch-nob::after { content: ''; position: absolute; background: rgba(97, 97, 97, 1); border-radius: 2px; transform: rotate(45deg); } .my-switch-nob::before { height: 15.5px; width: 1px; top: calc(50% - 8px); left: calc(50% - 0.5px); } .my-switch-nob::after { height: 1px; width: 15.5px; top: calc(50% - 0.5px); left: calc(50% - 8px); } /* 选中状态:开关容器背景变色 */ .my-tgl input[type="checkbox"]:checked ~ .my-switch { background: rgba(0, 122, 122, 1); } /* 选中状态:滑块右移 */ .my-tgl input[type="checkbox"]:checked ~ .my-switch .my-switch-nob { left: 18px; } /* 选中状态:叉号转为勾选样式 */ .my-tgl input[type="checkbox"]:checked ~ .my-switch .my-switch-nob::before { height: 12.5px; top: calc(55% - 6.5px); left: calc(60% - 0.5px); background: rgba(37,127,57,1); } .my-tgl input[type="checkbox"]:checked ~ .my-switch .my-switch-nob::after { width: 6px; top: calc(95% - 7.5px); left: calc(22.5% - 1.5px); background: rgba(37,127,57,1); }
关键适配说明
- 以
.my-tgl为容器前缀,避免样式污染其他组件 - 使用兄弟选择器
~关联复选框选中状态与开关容器的样式变化 - 将原示例中的结构选择器替换为你的类名:
div→.my-switch、label→.my-switch-nob - 保留原示例的过渡动画、圆角设计及勾选/叉号的形态切换逻辑
内容的提问来源于stack exchange,提问作者Urbycoz
相关产品推荐
相关产品推荐

