iOS Switches in CSS
Building Game Play Color gives me many opportunities and much encouragement to see explore what’s possible with modern CSS. Most recently, I found myself wanting a near-native iOS enable/disable switch for a forthcoming feature.
While it’s not perfect, it turns out that, with a little tinkering, something pretty good can be achieved (go ahead, try turning it on):
As one might hope, the HTML required is incredibly simple and looks something like this:
<div id="switch" class="setting-switch"></div>
With all the complexity remaining firmly in the CSS:
.setting-switch
{
transition: 300ms ease-in-out;
position: relative;
width: 46px;
height: 28px;
border-radius: 28px;
background-color: white;
margin: 10px;
border: 2px solid #E6E6E6;
}
.setting-switch:before
{
transition: 300ms ease-in-out;
content: '';
display: block;
width: 28px;
height: 28px;
border-radius: 28px;
background-color: #fff;
position: absolute;
top: 0;
left: 0;
box-shadow: 0 6px 4px rgba(0, 0, 0, 0.1), 0 -1px 2px rgba(0, 0, 0, 0.1);
}
.setting-switch.on
{
transition: 300ms ease-in-out;
background-color: #4CD964;
border: 2px solid #4CD964;
}
.setting-switch.on:before
{
transition: 300ms ease-in-out;
left: 18px;
}
The JavaScript itself is also simple when using something like JQuery:
var s = $("#switch")
s.click(function() {
s.toggleClass("on");
});
If you’re interested in playing further with the source, take a look at the JSFiddle.