I have seen code that applies to a simple input-label pair:
HTML
<input type="checkbox" id="toggle" class="checkbox" />
<label for="toggle" class="switch"></label>
CSS
.switch {
position: relative;
display: inline-block;
width: 40px;
height: 20px;
background-color: rgba(0, 0, 0, 0.25);
border-radius: 20px;
transition: all 0.3s;
}
.switch::after {
content: '';
position: absolute;
width: 18px;
height: 18px;
border-radius:50%;
background-color: white;
top: 1px;
left: 1px;
transition: all 0.3s;
}
.checkbox:checked + .switch::after {
left : 20px;
}
.checkbox:checked + .switch {
background-color: #7983ff;
}
.checkbox {
display : none;
}
Working example from above:
https://codepen.io/lawrencelove/pen/xxBWpBj
But unfortunately, when using an ASP.NET asp:checkbox
control, it renders the HTML differently.
HTML
<span class="checkbox"><input id="toggle" type="checkbox" name="ctl00$ucSiteVersion$toggle" checked="checked">
</span>
<label for="toggle" class="switch"></label>
In this case, because the input
control is nested within the span
tags, and this seems to cause it to no longer match the combinator selector.
Broken example from above with the span
tags:
https://codepen.io/lawrencelove/pen/MWxVrxm
I tried various combinations of adjacent siblings and descendants, but I couldn't get it to play nicely with the inclusion of the closing span
tag. I also tried referencing #toggle:checked
instead of .checkbox:checked
, but that didn't work either.
How can I target .switch
from a checkbox
control within the span
tag?
Replace this:
.checkbox:checked + .switch::after {
left : 20px;
}
.checkbox:checked + .switch {
background-color: #7983ff;
}
with this:
span:has(> input:checked) + .switch::after {
left : 20px;
}
span:has(> input:checked) + .switch {
background-color: #7983ff;
}