问题
Is there a way to still have the Bootstrap 4 custom checkbox styling without using the id
on the input and the attribute for
on the label? The styling for checked is not there when you remove it.
Example:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="custom-control custom-checkbox mb-3">
<input type="checkbox" class="custom-control-input" id="customControlValidation1" required>
<label class="custom-control-label">Check this custom checkbox</label>
</div>
I've tried wrapping the input with label, but that doesn't seem to do anything either. Is there a way I could avoid giving the input a static id and still get the Boostrap styled checkbox? Thanks!
回答1:
Yes you can do but for that you need to do some custom CSS as well.
Please try below CSS
.custom-checkbox{
position: relative;
}
.custom-checkbox input{
visibility: hidden;
margin-right: 8px;
}
.custom-label:before,.custom-label:after{
width: 16px;
height: 16px;
content: "";
border: 1px solid;
display: inline-block;
position: absolute;
left: 0;
top: 0px;
border: #adb5bd solid 1px;
transition: background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
border-radius: .25rem;
}
.custom-checkbox input:checked + .custom-label:before{
border-color: #007bff;
background-color: #007bff;
}
.custom-checkbox input:checked + .custom-label:after{
width: 4px;
border: 2px solid #ffffff;
height: 8px;
border-top: none;
border-left: none;
transform: rotate(40deg);
left: 6px;
top: 3px;
}
<label class="custom-checkbox"><input type=checkbox name=chkbx1> <span class="custom-label">Label here</span></label>
.
回答2:
Here is simplest solution. Label should be used as wrapper for checkbox being clickable.
<div class="custom-control custom-checkbox">
<label><input type="checkbox" name="checkbox-name" class="custom-control-input">
<div class="custom-control-label"></div>
</label>
</div>
回答3:
no that is not possible to remove ID
and For
.
because the for="customControlValidation1"
attribute allow us to click the id="customControlValidation1"
means when we click the label it considers checkbox click and checkbox state will change.
回答4:
i sure this work perfectly
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="custom-control custom-checkbox mb-3">
<input type="checkbox" class="custom-control-input" id="customControlValidation1" required>
<label class="custom-control-label" for="customControlValidation1">Check this custom checkbox</label>
</div>
来源:https://stackoverflow.com/questions/57890808/bootstrap-custom-checkbox-without-attribute-for