CSS-only Styling For A Checkbox `input` As A Flip Switch, And Keep Its Existing `label`
How can I (CSS-only) style an input with type='checkbox', and keep the existing label declared for that input element?
Solution 1:
if you can change the sequence in label
and input
, here is an idea.
you can change the colors and add animation as per your requirement.
label{
position:relative;
display:block;
width:200px;
}
label:before{
content:'off';
width:50px;
height:20px;
background:#eee;
border-radius:50px;
position:absolute;
right:0
}
label:after{
content:'';
width:18px;
height:18px;
background:#333;
border-radius:50px;
position:absolute;
right:1px;
top:1px;
}
input:checked + label:before{
content:'on';
text-indent: 25px;
}
input:checked + label:after{
right:29px;
top:1px;
}
<p id="lorem-ipsum">
<input type="checkbox" id="dolor-sit-amet" name="dolor" />
<label for="dolor-sit-amet">Dolor sit amet</label>
</p>
Solution 2:
The :before
and :after
selectors can create some of the content. By adding another element (for example, a span
) that can be styled to appear as the “slider” of the switch.
Then, the containing element – which can be the label
itself! – can also have :before
and :after
selectors used to style the “socket” in which the slider moves.
input[type=checkbox].switch {
display: none;
}
label.switch.socket {
position: relative;
width: auto;
text-indent: 6.0ex;
}
span.switch.slider {
display: inline-block;
}
label.switch.socket span.switch.slider:before {
content: "off";
text-indent: 2.3ex;
width: 5.5ex;
height: 2.2ex;
color: White;
background: DimGray;
border-radius: 5.5ex;
position: absolute;
left: 0;
}
label.switch span.switch.slider:after {
content: "";
width: 2.0ex;
height: 2.0ex;
background: Gainsboro;
border-radius: 5.5ex;
position: absolute;
left: 0.1ex;
top: 0.1ex;
transition: 0.2s;
}
label.switch.socket input[type=checkbox]:checked + span.slider:before {
content: "on";
text-indent: 0.5ex;
color: Black;
background: DarkGray;
}
label.switch.socket input[type=checkbox]:checked + span.slider:after {
left: 3.4ex;
}
<p>
<label class="switch socket">
<input type="checkbox" class="switch" name="lorem" />
<span class="switch slider" />
Lorem ipsum
</label>
<label class="switch socket">
<input type="checkbox" class="switch" name="dolor" checked />
<span class="switch slider round" />
Dolor sit amet
</label>
</p>
(Thanks to @gosi123 and @aje for suggestions that came close enough to help me formulate this answer.)
Post a Comment for "CSS-only Styling For A Checkbox `input` As A Flip Switch, And Keep Its Existing `label`"