26 Mar 2023

Using HTML and CSS to create a custom toggle switch

A toggle switch is a UI element that allows users to switch between two states, typically on or off. While there are many pre-built toggle switches available in HTML and CSS, creating a custom toggle switch can give your website or application a unique look and feel. In this blog, we'll go through the steps of creating a custom toggle switch using HTML and CSS.

Step 1: Create the HTML structure

To create the HTML structure for our toggle switch, we'll use a div element with a class of "toggle-switch". Inside this div, we'll create two label elements with a for attribute that corresponds to an input element with a type of checkbox. We'll also add a span element with a class of "slider" to act as the sliding switch element.

<div class="toggle-switch">
  <label for="toggle-switch-checkbox">On</label>
  <input type="checkbox" id="toggle-switch-checkbox">
  <span class="slider"></span>
  <label for="toggle-switch-checkbox">Off</label>
</div>

Step 2: Style the toggle switch with CSS

Now that we have the basic structure of our toggle switch, we can use CSS to style it. We'll start by setting the width and height of the toggle switch and positioning the slider element. We'll also set the background color of the slider and add a border to make it stand out.

.toggle-switch {
  position: relative;
  width: 60px;
  height: 30px;
}

.slider {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  border: 1px solid #777;
}

Next, we'll style the label elements to make them appear on either side of the slider. We'll use the CSS float property to align the "On" label to the left and the "Off" label to the right.

.toggle-switch label {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 50%;
  text-align: center;
  line-height: 30px;
  color: #fff;
  float: left;
  background-color: #428bca;
  cursor: pointer;
}

.toggle-switch label:last-of-type {
  float: right;
  background-color: #777;
}

Finally, we'll use CSS to style the input element and hide it from view. We'll also use the :checked pseudo-class to move the slider to the opposite side when the input is checked.

.toggle-switch input {
  display: none;
}

.toggle-switch input:checked + .slider {
  transform: translateX(100%);
  background-color: #5cb85c;
}

Step 3: Test the toggle switch

Now that we've created and styled our custom toggle switch, it's time to test it out! Open your HTML file in a web browser and toggle the switch on and off. If everything is working correctly, the background color of the slider should change to green when the switch is in the "on" position.

Congratulations, you've created a custom toggle switch using HTML and CSS! With some additional CSS styling, you can further customize the look and feel of your toggle switch to fit the needs of your website or application.