This is the 28th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
preface
For front-end developers, checkboxes should be a common sight. Using the Checked properties of the checkbox, we can do a lot of nice things, and we used the checkbox for animation pauses. A few days ago also see foreign bosses use checkbok play a game: www.bryanbraun.com/2021/09/21/… “, is really admired, but for me this kind of vegetable chicken players, or can only achieve some simple things. You should be familiar with the switch button below, which has also spawned all sorts of fancy effects, such as the dark mode switch. Life million, master one, ten thousand! It’s not that easy.
I recommend you check out the codepen warehouse: the article cover effect, which was also recorded here! TQL codepen. IO/oliviale/PE…
The label
Here we use for to bind label and input
<input type="checkbox" id="toggle" class="offscreen" />
<label for="toggle" class="switch"></label>
Copy the code
Also make the input invisible
input {
display: none;
}
Copy the code
Beautify the label
Encountered checkbox beautification problem, basically is to consider using beautification labL instead of beautification input.
Set the background color, width and height, and rounded corners
.switch { display: inline-block; display:relative; width: 40px; height: 20px; Background: rgba(0, 0, 0, 0.25); border-radius: 20px; }Copy the code
The final effect is as follows:
Switch of the circle
There will be a circle on the label, initially on the left, and the effect is as follows. In fact, this can be achieved by using the pseudo-element +positon position.
This is postion: Absolute, with position at top1px and left1px. Also set rounded corners.
.switch:after { content: ""; position: absolute; width: 18px; height: 18px; border-radius: 18px; background-color: white; top: 1px; left: 1px; The transition: all 0.3 s; }Copy the code
Checked + Ball moving right
So if you click here and the circle goes to the right, there are two ways to do it
1. Still through positioning
When the checkbox is checked, top,left,bottom,right is set. It is necessary to set top and left to auto. The advantage of this is that you do not need to worry about the width of the label.
input[type="checkbox"]:checked + .switch:after {
top: auto;
left: auto;
bottom: 1px ;
right: 1px ;
}
Copy the code
You can set the width of the label to top and left
top: 1px;
left: 21px;
Copy the code
2.translateX
*transform: translateX(20px)*
Copy the code
Beautify the switched label
Add a background color
input[type="checkbox"]:checked + .switch {
background-color: #7983ff;
}
Copy the code
Effect:
Afterword.
It seems that this article is an introduction to a checkbox beautification effect, in fact, it is an article telling you how to beautify checkbox, the final idea is to rely on the binding effect of for, beautify label to achieve the final effect.