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>

CSS rules

Styling the div#cover element

	width: 100px;
	margin:0 auto;
	position: relative;

Styling the checkbox

	margin: 0px;
	width: 100%;
	height: 50px;
	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)

	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)

	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

#checkbox:checked ~ #bar

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

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