伪元素实现的复选框随label文本变长被挤压,如何用flex适配?
修复思路
问题的核心根因有两个:
- 文本容器没有设置宽度占比,长文本会占用flex容器的全部剩余空间,挤压复选框的布局位置
- 对勾伪元素
::after的定位规则写死了top:0,当label被多行文本撑高后,对勾位置和复选框::before错位
具体修改点
仅需要调整CSS规则即可:
- 给
.label-wrapper添加宽占比和换行规则,保证长文本自动折行 - 调整对勾伪元素的定位规则,让它永远和复选框重合
- 可选:如果需要复选框和第一行文本顶部对齐,可修改
.label的align-items规则为flex-start
修改后完整代码
CSS
.outter-wrapper { width: 200px; border: 1px solid black; } .wrapper { display: inline-flex; min-height: 1.5rem; padding: 8px 24px 8px 0px; width: 100%; box-sizing: border-box; } .input { position: absolute; z-index: -1; visibility: hidden; } .label-wrapper { line-height: 1.5rem; flex: 1; margin-right: 12px; word-break: break-word; } .label { position: relative; margin-bottom: 0; display: flex; margin-left: 0; margin-right: 24px; flex-direction: row-reverse; justify-content: space-between; flex: 1; align-items: center; } .label:before { display: block; width: 20px; height: 20px; content: ""; background-color: #fff; border: 1px solid black; border-radius: 4px; flex: none; } .label:after { position: absolute; display: block; height: 20px; width: 20px; content: ""; background-repeat: no-repeat; background-position: center center; background-size: 80%; right: 0; top: calc(50% - 10px); } input[type="checkbox"]:checked~.label::after { background-image: url("https://cdn-icons-png.flaticon.com/512/447/447147.png"); }
HTML
<div class="outter-wrapper"> <div class="wrapper"> <input class="input" name="checkbox2" id="checkbox2" type="checkbox"> <label class="label" for="checkbox2"> <div class="label-wrapper"> Option 1Option 1Option 1Option 1Option 1 </div> </label> </div> </div>
效果验证
修改后不管文本长度是多少,复选框都不会被挤压,对勾永远和复选框精准对齐,短文本、多行文本场景都可以正常适配。
内容的提问来源于stack exchange,提问作者cts
相关产品推荐
相关产品推荐

