Implement Toggle Switch Button Effect with CSS

In web page production, the toggle switch button is a button effect that is often used. So how to implement the Toggle Switch button effect with CSS? In general, we control the state and style of the switch according to the checked attribute of the form checkbox.

How to Implement the Toggle Switch Button Effect with CSS

We need to set up a checkbox form, hide it with the visibility attribute, and then use the label element to show the effect of the toggle button. A checkbox and its bound label should have the same names as id="switch" and for="switch".

HTML Setting

<div class="wrap">
	<input type="checkbox" id="switch" checked />
	<label for="switch">
		<span class="txt" turnOn="On" turnOff="Off"></span>

CSS Example

	input[type=checkbox] {
		height: 0;
		width: 0;
		visibility: hidden;
		cursor: pointer;
		width: 110px;
		height: 50px;
		background: grey;
		display: block;
		border-radius: 50px;
		position: relative;
	.txt::after {
		content: '';
		position: absolute;
		top: 5px;
		left: 5px;
		width: 40px;
		height: 40px;
		line-height: 40px;
		text-align: center;
		background: #fff;
		border-radius: 50%;
		transition: 0.3s;
	.txt::after {
		display: block;
		color: #fff;
		font-weight: bold;
		box-sizing: border-box;
	.txt::before {
		content: attr(turnOn);
		color: #fff;
	.txt::after {
		content: attr(turnOff);
		color: #ccc;
		right: 5px;
		left: inherit;
	input:checked+label {
		background: #20c997;
	label:active:after {
		width: 40%;
	input:checked+label:after {
		left: calc(100% - 5px);
		transform: translateX(-100%);

Leave a reply