ArticleZip > 3 State Css Toggle Switch

3 State Css Toggle Switch

If you're looking to add some interactive flair to your website, a CSS Toggle Switch is a fantastic option. In this article, we'll guide you through creating a stylish and functional 3-state CSS Toggle Switch that you can easily implement on your site.

To get started, let's dive into the code:

HTML Structure:
First, create the HTML structure for the toggle switch. You can start by adding a container div and within it, include three input elements, each with a type of checkbox.

Html

<div class="toggle-switch">
  
  
  
  <label for="state1"></label>
  <label for="state2"></label>
  <label for="state3"></label>
</div>

CSS Styling:
Next, let's style the toggle switch using CSS. Here's a simple example to get you started:

Css

.toggle-switch {
  display: inline-block;
  position: relative;
  width: 90px;
  height: 34px;
}

input[type="checkbox"] {
  display: none;
}

label {
  display: block;
  position: absolute;
  cursor: pointer;
  width: 30px;
  height: 100%;
  background-color: #ccc;
}

#state1:checked ~ label:nth-of-type(1) {
  background-color: #4CAF50;
}

#state2:checked ~ label:nth-of-type(2) {
  background-color: #FFC107;
}

#state3:checked ~ label:nth-of-type(3) {
  background-color: #F44336;
}

JavaScript Functionality:
For the JavaScript part, you can add functionality to switch among the three states when the labels are clicked. Here's a simple script to achieve this:

Javascript

document.querySelectorAll('label').forEach((label) =&gt; {
  label.addEventListener('click', () =&gt; {
    document.querySelectorAll('input[type="checkbox"]').forEach((checkbox) =&gt; {
      checkbox.checked = false;
    });
    label.previousElementSibling.checked = true;
  });
});

By combining HTML, CSS, and a touch of JavaScript, you can create a visually appealing 3-state CSS Toggle Switch that will enhance the interactivity of your website. Feel free to further customize the styling and behavior to suit your design needs.

In conclusion, implementing a 3-state CSS Toggle Switch is a fun and practical way to add user-friendly features to your website. With a bit of coding magic, you can create a dynamic element that engages your visitors and provides a seamless user experience. So, roll up your sleeves, dive into the code, and let your creativity shine!

×