Skip to Content

With Android 4.0 a variety of new, nice interface elements were introduced. One of my personal favorites is the new toggle switch. So, I thought I’d give a shot at recreating it in a HTML/CSS. Take a peek.

Click it to toggle it: OffOn

Click it to toggle it: OffOn

HTML

<p>Click it to toggle it: <a class="toggler on" href="#toggle"><span class="tog_off">Off</span><span class="tog_on">On</span></a></p>
<p>Click it to toggle it: <a class="toggler off" href="#toggle"><span class="tog_off">Off</span><span class="tog_on">On</span></a></p>

CSS

a.toggler {
	display:inline-block;
	color:#666;
	background-color:#e6e6e6;
	padding:0;
	text-transform:uppercase;
	font-size:10px;
	line-height:1em;
	font-family: Helvetica, Arial, sans-serif;
	text-decoration:none;
	overflow: hidden;
}
a.toggler span {
	display:inline-block;
	width:2em;
	text-align:center;
	position:relative;
	-moz-transition:all 0.2s ease-out;
	-webkit-transition:all 0.2s ease-out;
}
a.toggler.on span.tog_on {
	background-color:#3cf;
	color:white;
	margin-left:1.5em;
	padding:4px 0.75em 4px 1.25em;
}
a.toggler.off span.tog_off {
	background-color:#888;
	color:white;
	margin-right:1.5em;
	padding:4px 1.25em 4px 0.75em;
}
a.toggler.on span.tog_on:before {
	content: " ";
	display: block;
	position:absolute;
	width:0;
	height:0;
	overflow:hidden;
	border-style:solid;
	border-width:18px 6px 0 0;
	border-color:#e6e6e6 transparent transparent;
	top:0;
	left:0;
}
a.toggler.off span.tog_off:after {
	content: " ";
	display: block;
	position:absolute;
	width:0;
	height:0;
	overflow:hidden;
	border-style:solid;
	border-width:0 0 18px 6px;
	border-color:transparent transparent #e6e6e6 transparent;
	top:0;
	right:0;
}
a.toggler.on:hover span.tog_off,
a.toggler.off:hover span.tog_on {
	color:#000;
}
a.toggler.on span.tog_off {
	display:none;
}
a.toggler.off span.tog_on {
	display:none;
}
a.toggler.on:hover span {
	position:relative;
	left:2px;
}
a.toggler.off:hover span {
	position:relative;
	left:-2px;
}

Javascript

// just a bit of JS to make it toggle for the demo
$(function(){
	$('a.toggler').click(function(){
		if ($(this).hasClass('on')) {
			$(this).removeClass('on').addClass('off');
		} else if ($(this).hasClass('off')) {
			$(this).removeClass('off').addClass('on');
		}
		return false;
	});
});