I am working on a switch checkbox input and currently the style changes when I click on the switch knob only. But, I cannot figure out how to make the switch style change when the switch input is checked and slider is clicked instead of the knob itself.
<input type="checkbox" id="toggle"/>
<div>
<label for="toggle"></label>
</div>
input[type="checkbox"] {
display: none;
}
/* style switch when 'unchecked' */
div {
position: relative;
width: 42px;
height: 26px;
background: #cccccc;
border-radius: 20px;
}
/* style switch knob */
label {
position: absolute;
width: 22px;
height: 22px;
background: #ffffff;
top: 2px;
left: 2px;
border-radius: 50%;
cursor: pointer;
}
/* style slider and knob when switch is 'checked' */
input[type="checkbox"]:checked ~ div label {
-webkit-transform: translateX(16px);
-ms-transform: translateX(16px);
transform: translateX(16px);
}
input[type="checkbox"]:checked ~ div {
background: #0071d0;
}
/* style knob when switch is unchecked. */
label::before {
position: absolute;
content: '1F5D9';
width: 10px;
height: 10px;
left: 3px;
top: -1px;
}
/* style knob when switch is checked. */
input[type="checkbox"]:checked ~ div label::before {
position: absolute;
content: '2713';
width: 10px;
height: 10px;
left: 5px;
}
Can someone take a look and help me with this? Thanks!
3
Answers
Clicking the
label
element has the same effect as clicking the checkbox. This means that rather than wrapping yourlabel
in adiv
, you need thelabel
to wrap aspan
instead. The label needs to be the wrapper, if you like.However, I prefer this simplified version without a glyph inside the switch.
Just playing around with your code gave me this. As said above, the label needs to be the wrapper.
Brett’s is a nicer answer, though.
To change the switch style when the switch input is checked and the slider is clicked instead of the knob itself, you can modify your HTML and CSS as follows:
Add this in your code and try to run.