如何调整CSS::before/::after伪元素位置 将自定义复选框移到标签右侧
调整方案
你只需要修改两处CSS规则即可实现复选框右置的效果:
- 将
.wrapper原本给左侧预留的内边距调整到右侧,给右侧复选框预留显示空间 - 将伪元素
::before和::after的左侧定位逻辑改为右侧定位
修改后完整代码如下:
CSS代码
.wrapper { display: inline-flex; min-height: 1.5rem; /* 把原来的padding-left改为padding-right,预留足够空间放40px尺寸的复选框 */ padding-right: 2.5rem; /* 修正原代码中1和rem之间的多余空格 */ margin-right: 1rem; } .label { position: relative; margin-bottom: 0; } .label:before { position: absolute; top: 4px; /* 把原来的left:-24px改为right:-24px */ right: -24px; display: block; width: 20px; height: 20px; pointer-events: none; content: ""; background-color: red; } .label:after { position: absolute; top: 4px; /* 把原来的left:-24px改为right:-24px */ right: -24px; display: block; width: 40px; height: 40px; content: ""; background-repeat: no-repeat; background-position: center center; background-size: 50% 50%; }
HTML代码(无需改动)
<div class="wrapper"> <label class="label"> <div class="label-wrapper">In progress</div> </label> </div>
如果需要调整复选框和文本之间的间距,只需要修改两个伪元素的right属性数值即可,数值越大复选框离文本越远。
内容的提问来源于stack exchange,提问作者cts
相关产品推荐
相关产品推荐

