隐藏checkbox输入框时如何设置label元素间的外边距
解决Checkbox隐藏后Label间距不生效的问题
这问题我之前也碰到过,核心原因是label默认是行内元素(inline),行内元素的上下margin是不会生效的,只有左右margin能起作用。当checkbox可见时,它的布局会改变label的显示上下文,才让margin看起来生效了。咱们可以用下面的方法来调整:
方案1:将Label转为块级/行内块元素(推荐)
修改CSS,给label设置display: block或者display: inline-block,这样margin就能正常发挥作用了,同时可以去掉HTML里的<br>标签,用CSS控制间距会更优雅:
修改后的HTML:
<div class="dropdown"> <span class="tag"> <span class="tag-text">Talla</span> <span class="tag-caret">▼</span> </span> <div class="dropdown-content"> <input type="checkbox" name="talla[]" id="36" class="filtro"> <label for="36" class="label">36</label> <input type="checkbox" name="talla[]" id="37" class="filtro"> <label for="37" class="label">37</label> <input type="checkbox" name="talla[]" id="38" class="filtro"> <label for="38" class="label">38</label> </div> </div>
垂直排列的CSS:
input[type="checkbox"] { display:none; } .label { display: block; /* 转为块级元素,独占一行 */ padding:3px; margin:10px 0; /* 上下margin生效,左右可按需调整 */ border:1px solid lightslategrey; border-radius: 1px; cursor: pointer; /* 加上鼠标指针,提升交互体验 */ }
如果想让label横向排列,就改用display: inline-block:
.label { display: inline-block; padding:3px; margin:10px; border:1px solid lightslategrey; border-radius: 1px; cursor: pointer; }
方案2:用visibility:hidden代替display:none(不推荐,仅作参考)
如果不想改变label的显示类型,也可以把checkbox的display:none改成visibility:hidden; position: absolute;,这样checkbox仍然占据文档流但不可见,label的margin也能生效。不过这种方式会留下空白占位,不如方案1干净:
input[type="checkbox"] { visibility:hidden; position: absolute; } .label { padding:3px; margin:10px; border:1px solid lightslategrey; border-radius: 1px; }
推荐用方案1,既解决了间距问题,又让布局更可控,还能优化用户的交互体验~
内容的提问来源于stack exchange,提问作者Juan Antonio Rodríguez Gabriel
相关产品推荐
相关产品推荐

