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;
}
<pid="lorem-ipsum"><inputtype="checkbox"id="dolor-sit-amet"name="dolor" /><labelfor="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.socketspan.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.switchspan.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.socketinput[type=checkbox]:checked + span.slider:before {
content: "on";
text-indent: 0.5ex;
color: Black;
background: DarkGray;
}
label.switch.socketinput[type=checkbox]:checked + span.slider:after {
left: 3.4ex;
}
<p><labelclass="switch socket"><inputtype="checkbox"class="switch"name="lorem" /><spanclass="switch slider" />
Lorem ipsum
</label><labelclass="switch socket"><inputtype="checkbox"class="switch"name="dolor"checked /><spanclass="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`"