Creating a toggle button using html and css without any javascript

Creating a toggle button using html and css without any javascript

4 min. read

HTML markup

<div id="cover">
	<input type="checkbox" id="checkbox">
	<div id="bar"></div>
	<div id="knob"></div>
</div>

CSS rules

Styling the div#cover element

#cover
{
	width: 100px;
	height:50px;
	margin:0 auto;
	position: relative;
}

Styling the checkbox

#checkbox
{
	margin: 0px;
	width: 100%;
	height: 50px;
	cursor:pointer;
	opacity:0;
	position: relative;
	z-index: 3;
}

After styling the checkbox

  1. it covers the whole div#cover element
  2. it is invisible because of opacity : 0 css rule

Styling div#bar element (green colored bar)

#bar
{
	position: absolute;
	top: 0px;
	left: 0px;
	right: 0px;
	bottom: 0px;
	background-color: #3dd897;
	z-index: 1;
	border-radius: 50px;
}

Styling div#knob element (white knob button)

#knob
{
	position: absolute;
	top: 8px;
	left: 8px;
	width: 34px;
	height: 34px;
	background-color: #fff;
	border-radius: 50%;
	transition: left 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28), margin-left 0.3s ease, width 0.3s ease, border-radius 0.3s ease;
	box-shadow:0px 1px 1px #7d7d7d;
	z-index: 2;
}

Result of applying all above css

Phase 1

When there is click on checkbox (active state of checkbox) increase the width of knob button.

#checkbox:active ~ #knob
{
	width: 66px;
	border-radius: 20px;
}

Change in width of knob button

Phase 2

When checkbox is checked, move the knob button to right side ( ON position ) and change the color of green bar to blue.

#checkbox:checked ~ #knob
{
	left:58px;
}

#checkbox:checked ~ #bar
{
	background-color:#00bcd4;
}

On position of toggle button

Phase 3

Add this additional css, to prevent knob button from going out of blue bar on right side when checkbox is unchecked.

#checkbox:checked:active ~ #knob
{
	margin-left:-32px;
}

In above css code 32px is obtained as 66px (width of knob button in active state of checkbox) - 34px (normal width of knob button), " - " sign is used to move the knob button to left side.

See result in the fiddle below

Write comments