How do I create a CSS-only toggle switch?
Antek N
antek n profile pic

Creating a CSS-only toggle switch involves using thecheckbox input element and styling it with CSS to create the switch appearance. Here's a step-by-step explanation of how you can create a CSS-only toggle switch: HTML Markup: Start by creating the HTML structure for your toggle switch. Use the element to associate the label text with the checkbox input.

1
2
3
4
label class="toggle-switch">
  <input type="checkbox">
  <span class="slider"></span>
</label>

CSS Styling: Apply the following CSS styles to create the toggle switch:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
oggle-switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.toggle-switch input {
  display: none;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: 0.4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: 0.4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

In this example, the.toggle-switch class represents the container for the toggle switch. It is given a specific width and height to define the size of the switch. The.toggle-switch input styles hide the checkbox input by settingdisplay: none;. The.slider class represents the switch itself. It is positioned absolutely within the container usingposition: absolute;. Thebackground-color andborder-radius properties define the appearance of the switch. Thetransition property adds a smooth animation effect to the switch. The.slider:before class represents the knob of the switch. It is positioned absolutely within the switch container. Thecontent property is used to insert an empty pseudo-element. Theheight,width,background-color, andborder-radius properties define the appearance of the knob. Theinput:checked + .slider selector targets the switch element when the associated checkbox input is checked. This allows you to apply specific styles when the switch is toggled. Theinput:checked + .slider:before selector targets the knob element when the associated checkbox input is checked. This allows you to adjust the position of the knob when the switch is toggled. By applying these CSS styles, the checkbox input and the associated label will be visually transformed into a toggle switch. The switch will change its appearance when toggled on or off. Adjust the styles, colors, and sizes as needed to match your design requirements.