在Bootstrap 4中将自定义复选框图标放置在标签右侧

8
我尝试了一切,但是无法将复选框放在标签右侧。如果是普通类型的复选框,我可以将其移动到标签右侧。但是对于自定义复选框类型,我无法做到同样的效果。

<div class="custom-control custom-checkbox mb-3">
  <input type="checkbox" class="custom-control-input" id="customCheck" name="example1">
  <label class="custom-control-label" for="customCheck">Label</label>
</div>

3个回答

13

使用伪元素创建自定义复选框,因此它们的定位需要相对于标签进行调整。

.custom-control.custom-checkbox{padding-left: 0;}

label.custom-control-label {
  position: relative;
  padding-right: 1.5rem;
}

label.custom-control-label::before, label.custom-control-label::after{
  right: 0;
  left: auto;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="custom-control custom-checkbox mb-3">
  <input type="checkbox" class="custom-control-input" id="customCheck" name="example1">
  <label class="custom-control-label" for="customCheck">Label</label>
</div>


6
之前的@serg-chernata的答案在使用custom-switch时对我似乎不起作用。这里是一个我成功运行的示例。 CSS
div.custom-control-right {
    padding-right: 24px;
    padding-left: 0;
    margin-left: 0;
    margin-right: 0;
}
div.custom-control-right .custom-control-label::after{
    right: -1.5rem;
    left: auto;
}
div.custom-control-right .custom-control-label::before {
    right: -2.35rem;
    left: auto;
}

HTML

<div class="custom-control custom-control-right custom-switch">
    <input type="checkbox" class="custom-control-input" disabled id="customSwitch2">
    <label class="custom-control-label" for="customSwitch2">Right switch element</label>
</div>

JsFiddle

https://jsfiddle.net/2cmbq9r0/

截图

向左和向右切换开关

编辑:将left:initial更改为left:auto,以使其与IE11兼容。


0

如果您可以接受以下内容:

  1. 标签和复选框之间的距离更大
  2. 使用基本的form-check类,而不是custom-control

那么一个替代方案是使用col-right类将复选框移动到表单的远侧。在某些情况下,我发现将标签和输入元素分别对齐到最左侧和最右侧提供了一个漂亮的一致外观。

<div class="row form-row">
  <div class="col">
    <label class="form-check-label" for="customCheck">Label</label>
  </div>
  <div class="col-right">
    <input type="checkbox" class="form-check-input" id="customCheck" name="example1">
  </div>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接