Bootstrap 4 如何将自定义checkbox/switch控件设置为-sm小号尺寸?
问题原因
Bootstrap 4的custom-control系列组件本身没有预设小号尺寸的内置类,form-control-sm是针对原生表单控件设计的样式类,无法作用于自定义开关的伪元素样式,所以添加后不会生效。
解决方案
通过自定义CSS适配小号开关的尺寸,即可匹配input-group-sm的高度,实现和周边输入框、按钮对齐的效果:
1. 添加自定义CSS
/* 自定义小号switch样式 */ .custom-switch.custom-switch-sm { min-height: auto; padding-left: 2rem; } .custom-switch.custom-switch-sm .custom-control-label { line-height: 1.5; padding-top: 0.1rem; } .custom-switch.custom-switch-sm .custom-control-label::before { height: 1.2rem; width: 2rem; top: 0.1rem; left: -2rem; border-radius: 0.6rem; } .custom-switch.custom-switch-sm .custom-control-label::after { width: calc(1.2rem - 4px); height: calc(1.2rem - 4px); top: calc(0.1rem + 2px); left: calc(-2rem + 2px); border-radius: 50%; } .custom-switch.custom-switch-sm .custom-control-input:checked ~ .custom-control-label::after { transform: translateX(0.8rem); } /* 适配input-group-text内边距,若需兼容不支持:has选择器的浏览器,可给对应input-group-text添加自定义类设置padding */ .input-group-sm .input-group-text:has(.custom-switch-sm) { padding: 0.25rem 0.5rem; }
2. 修改HTML结构
给custom-switch元素新增自定义的custom-switch-sm类,同时移除input和label上无效的form-control-sm类即可:
<div class="input-group input-group-sm"> <span class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-table"></i> </span> </span> <span class="input-group-prepend"> <span class="input-group-text"> <span class="custom-control custom-switch custom-switch-sm"> <input type="checkbox" class="custom-control-input" aria-autocomplete="none" autocomplete="off" id="DefineAttributes" name="DefineAttributes" title="Define the attributes" value="true"> <label class="custom-control-label" for="DefineAttributes"></label> </span> </span> </span> <input type="text" class="form-control form-control-sm" aria-autocomplete="none" autocomplete="off" id="Attributes" name="Attributes" placeholder="Attributes ..." value="something"> <span class="input-group-append"> <a class="btn btn-sm btn-outline-primary " title="Select attributes" href="#">Select</a> </span> </div>
内容的提问来源于stack exchange,提问作者Zoltan Hernyak
相关产品推荐
相关产品推荐

