First seen in 2007 when the first iphone came out, those nifty iOS switches that are used until today are undeniably nice and modern looking. Having them in your web app or mobile app can add a nice UI experience and give it a touch of modernity.
Let's see how we can go about designing them with a little bit of css code and 3 html elements only.
We'll start by adding a label element, with an input and an i element.
HTML
<label class="ios-switch">
<input type="checkbox">
<i></i>
</label>
Now the CSS
We'll start with the label container first
.form-switch {
display: inline-block;
cursor: pointer;
}
We need to hide the input element as we don't want to see it as a classic checkbox element.
.form-switch input {
display: none;
}
Then we style the i tag inside. We'll set the dimensions of the button, with some margin and transition effects. We also want the background to be off-white.
.form-switch i {
position: relative;
display: inline-block;
margin-right: 0.5rem;
width: 46px;
height: 26px;
background-color: #e6e6e6;
border-radius: 23px;
vertical-align: text-bottom;
transition: all 0.3s;
}
We'll also need to add a pseudo-element ::before. When the switch is turned off (default) it has a white background.
.form-switch i::before {
content: "";
position: absolute;
left: 0;
width: 42px;
height: 22px;
background-color: #fff;
border-radius: 11px;
transform: translate3d(2px, 2px, 0) scale3d(1, 1, 1);
transition: all 0.3;
}
The ::after pseudo-element will create the round switch "handle".
.form-switch i::after {
content: "";
position: absolute;
left: 0;
width: 22px;
height: 22px;
background-color: #fff;
border-radius: 11px;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.24);
transform: translate3d(2px, 2px, 0);
transition: all 0.2s ease-in-out;
}
Here we will set the width of the switch when it is activated, with some 3d transforms
.form-switch:active i::after {
width: 28px;
transform: translate3d(2px, 2px, 0);
}
.form-switch:active input:checked + i::after {
transform: translate3d(16px, 2px, 0);
}
Then we'll add the background color of the switch when it is turned on
.form-switch input:checked + i {
background-color: #5bda4e;
}
Finally we'll set the pseudo-elements for the i tag when we turn on the switch so it gives an effect of opening up like the iPhone does.
.form-switch input:checked + i::before {
transform: translate3d(18px, 2px, 0) scale3d(0, 0, 0);
}
.form-switch input:checked + i::after {
transform: translate3d(22px, 2px, 0);
}
That's it, you can use the code as you want and add it to your website or app. A cool idea would be to convert it into a react component. Enjoy!
My App (where is used the switch): https://flexrweb.com/octacore
The Github repo: https://github.com/urielbitton/octacore
Top comments (0)