如何在同一列中添加多组可独立选中的单选按钮
你当前代码中两组单选按钮样式不一致,是因为CSS仅对private、shared两个选项的label写了单独的样式规则,ATV组的两个选项label没有匹配到对应的样式规则导致的。同时原来包裹单选的容器用了flex横向布局,所以两组单选会排在同一行,不符合你要两行显示的需求。
修改步骤
第一步:调整CSS样式
找到页面<style>标签内的对应代码,做如下调整:
- 替换原有的
.container { display: flex; }样式,避免和Bootstrap自带的container类冲突,同时改为纵向排列:
.radio-group-container { display: flex; flex-direction: column; gap: 10px; }
- 删除原来单独给
label[for=private]、label[for=shared]写的两段样式,替换为通用的单选label样式:
.radio-label { position: relative; color: orangered; font-size: 20px; border: 2px solid orangered; border-radius: 5px; padding: 2px 8px; display: inline-flex; align-items: center; cursor: pointer; margin-right: 10px; }
原有input[type="radio"]:checked+label的选中样式规则不用修改,本身就是通用规则可以适配所有单选按钮。
第二步:调整HTML结构
找到单选按钮对应的HTML代码,做如下调整:
- 把包裹两组单选的容器类从
container改为radio-group-container - 给四个单选对应的label都加上
class="radio-label"
修改后的单选部分代码如下:
<div class="radio-group-container" style="padding-left: 0;padding-top: 5px;"> <div> <input type="radio" name="occupancy" id="private" checked="checked"> <label for="private" class="radio-label">Private</label> <input type="radio" name="occupancy" id="shared"> <label for="shared" class="radio-label">Shared</label> </div> <div> <input type="radio" name="atv" id="withatv" checked="checked"> <label for="withatv" class="radio-label">With ATV</label> <input type="radio" name="atv" id="withoutatv"> <label for="withoutatv" class="radio-label">Without ATV</label> </div> </div>
修改完成后两组单选就会上下分行显示,所有选项的样式完全一致,同时可以正常选择两组的组合选项。
内容的提问来源于stack exchange,提问作者MMunir. Asif
相关产品推荐
相关产品推荐

