Creating a toggle label using just CSS: a step-by-step guide

Recently, I was trying to create a toggle label using HTML, CSS, and JavaScript.

Here is the code snippet that I experimented with:

function genre_itemclick(item){
          if(item.classList.contains('light_blue_border_button')) {
              item.classList.remove('light_blue_border_button');
              item.classList.add('light_blue_button');
          }
          else{
              item.classList.remove('light_blue_button');
              item.classList.add('light_blue_border_button');
          }
  }
.light_blue_border_button{
    background-color: #FFFFFF;
    border-radius: 10px;
    height: 30px;
    border:2px solid #3CDEBF;
    text-align: center; 
    color: #3CDEBF;
}
.light_blue_button{
    background-color: #3CDEBF;
    border:2px solid #3CDEBF;
    height: 30px;
    border-radius: 10px;
    text-align: center;
    color: #ffffff;      
}
<div class="light_blue_border_button" onclick="genre_itemclick(this)">test</div>

However, I wanted to achieve this functionality using only HTML and CSS. So, I made another attempt in the following way. But unfortunately, it didn't work as expected.

body {padding:60px;}

.toggle-switch input[type=checkbox] {display:none}
.toggle-switch label {cursor:pointer;}
.toggle-switch label{
    background-color: #FFFFFF;
    border-radius: 10px;
    height: 30px;
    border: 2px solid #3CDEBF; 
}

.toggle-switch input[type="checkbox"]:checked + label{
      background-color: #3CDEBF;
    border: 2px solid #3CDEBF;
    height: 30px;
    border-radius: 10px;
    text-align: center;
    color: #ffffff;
}
<div class="toggle-switch">
  <input type="checkbox" id="chkTest" name="chkTest">
  <label>
    Test
  </label>
</div>

If anyone has insights or suggestions on how to resolve this issue, your help would be greatly appreciated. Thank you in advance!

Answer №1

To create a custom styled checkbox, you can use an input of type "checkbox" and style it based on its checked state.

One way to do this is by using a label element to toggle the checkbox on and off. This works because clicking on a label automatically focuses the corresponding input field.

/* Default styling */
label {
    background-color: #FFFFFF;
    border-radius: 10px;
    height: 30px;
    border:2px solid #3CDEBF;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #3CDEBF;
    padding: 6px 9px 7px 8px;
    margin-top: 20px;
    margin-left: 8px;
    cursor: pointer;
}

/* Hide checkbox (we use the label the trigger the checkbox) */
#foo {
  display: none;
}

/* Styling when checkbox is checked */
#foo:checked + label {
    background-color: #3CDEBF;
    border:2px solid #3CDEBF;
    height: 30px;
    border-radius: 10px;
    text-align: center;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
    margin-left: 8px;
    padding: 6px 9px 7px 8px;
    cursor: pointer;
}
<input id="foo" type="checkbox" />
<label for="foo">test</label>

Answer №2

Give this solution a try, it is tailored for your needs.

.toggle-switch input[type=checkbox] {display:none}
.toggle-switch label {cursor:pointer;}
.toggle-switch label{
    background-color: #FFFFFF;
    border-radius: 10px;
    height: 30px;
    border: 2px solid #3CDEBF; 
}

.toggle-switch input[type="checkbox"]:checked + label{
      background-color: #3CDEBF;
    border: 2px solid #3CDEBF;
    height: 30px;
    border-radius: 10px;
    text-align: center;
    color: #ffffff;
}
<div class="toggle-switch">
  <input type="checkbox" id="chkTest" name="chkTest">
  <label for="chkTest">
    Test
  </label>
</div>

Answer №3

Don't forget to specify the label for attribute with the ID of the checkbox it should be associated with!

<label for="idOfInputCheckBox">
and
<input type="checkbox" id="idOfInputCheckBox" />
.

Alternatively, you can place the input element inside the label tag so that clicking on the label will trigger the checkbox. Here's an example:

:root {
  --blue: #6495ed;
  --white: #fff;
}

label {
  display: block;
  text-align: center;
}
label input.toggleBox {
  display: none;
}
label .button {
  cursor: pointer;
  display: inline-block;
  padding: 20px 50px;
  margin: 10px auto;
  border: 1px solid var(--blue);
  border-radius: 10px;
  background-color: var(--blue);
}
label input.toggleBox:checked ~ .button {
  background-color: var(--white);
}
<label>
  <input type="checkbox" class="toggleBox" />
  <span class="button">some Text.</span>
</label>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to utilize AJAXToolKit and Jquery on a single webpage?

Is it possible to utilize both AJAXToolKit and jQuery on a single page? For example, let's say we have ScriptManager in the same page along with including ...

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...

The header, main content, and footer sections expand to occupy the entire page

I am in need of HTML structure that looks like the following: <header></header> <div id='main'></div> <footer></footer> I want all elements to be positioned relatively. The header and footer will have fixed h ...

Guide to positioning a div in the center while implementing animations through transition and transformation using scale

Creating a popup for my React app without relying on external libraries is my current project. I am experimenting with using transition and transform with scale to size the popup dynamically based on screen size and content, then center it on the screen. ...

Insufficient allocation - memory overflow in loopback.js

I encountered an issue while trying to fetch large data using loopback.js. The error message I received was: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory <--- Last few GCs ---> 45903 ms: Mark-sweep 1385.6 (14 ...

Storing the outcome of a connection in a variable using Node.js

I am facing an issue with saving a function return in a const so that I can utilize the information outside of the function scope. Below is a snippet of code to better explain my problem: const express = require('express') const app = express() ...

What is the best way to retrieve all of a user's records based on a specified selection

My HTML text input field looks like this: <input id="CustID" name="CustID" dir="rtl" value="<?php echo $CustID;?>" size="35" required="true" maxlength="9" > Whenever a user enters their number, I want a select box to display all tickets assoc ...

The issue with Node module @kenjiuno/msgreader is that it is unable to find the constructor for MsgReader

I've been having trouble getting the example code for parsing Outlook .msg files using @kenjiuno/msgreader to work. Despite successfully installing the module with npm, my code doesn't seem to function as expected: const fs = require('fs&apo ...

How do you trim a string and display the final 3 characters?

When dealing with a list of objects, I want to ensure that the chain of tasks does not become too long and break the table or appear aesthetically unpleasing. Therefore, my goal is to trim the tasks and display only the last 3. In the image below, multiple ...

How can I display a calendar with a complete month view using ng-repeat?

I was trying to replicate a table similar to the one shown in this image: (disregard the styling). I am struggling with how to properly format the data to create a similar table in HTML. $scope.toddlers = [ { "name": "a", "day": 1, "total": 3 }, { ...

How to remove a loop-rendered component from the DOM in Vue

My website has an image upload form where users can select multiple images. Once the images are selected, they are previewed and users can provide meta info such as Category and Type for each image. This functionality is implemented in the upload.vue file ...

Foundation Unveil Modal hidden from view

I'm currently integrating modals using Foundation 5 in a Rails application. The issue I'm facing is that the modal only works when the page is not scrolled down. If you scroll to the bottom of the page and try to activate the modal by clicking ...

Identify the moment a dialogue box appears using jQuery

I'm facing a situation where multiple dialogs are opened in a similar manner: $("#dialog").load(URL); $("#dialog").dialog( attributes, here, close: function(e,u) { cleanup } The chall ...

Tips for incorporating a Forgot/Reset password option into your #Firebase platform

In the project I'm working on, I am utilizing #AngularFire2. My goal is to incorporate a Reset / Forgot password link into the login page. Does anyone have suggestions on how to accomplish this task? I'm looking to get some insights from #AskFi ...

The Google Chrome console is failing to display the accurate line numbers for JavaScript errors

Currently, I find myself grappling with debugging in an angular project built with ionic framework. Utilizing ion-router-outlet, I attempt to troubleshoot using the Google Chrome console. Unfortunately, the console is displaying inaccurate line numbers mak ...

I am attempting to format an HTML form with proper indentation, but it seems to be eluding me

Struggling to design a custom registration form template, I'm facing an issue where paragraph spaces or indents are not being recognized by the program, even in the preview pane. Seeking assistance with this problem. I am attempting to position this ...

Tips for sending information from a controller to jQuery (Ajax) in CodeIgniter

Code snippet in controller: $rates['poor'] = 10; $rates['fair'] = 20; $this->load->view('search_result2', $rates); //Although I have attempted different ways, the only successful method is using the code above. Other ...

The error message states: "Cannot create element as the React object is not

Recently delving into the world of React and Material UI, I've been working on creating an AppBar with nested Tabs. Here's a snippet of my current approach: import {React, PropTypes, Component} from 'react'; import TodoTextInput from & ...

Combining various postponed JavaScript file imports in the HTML header into a single group

I've been facing an issue with my code structure, particularly with the duplication of header script imports in multiple places. Every time I need to add a new script, I find myself manually inserting <script type="text/javascript" src=&q ...

What could possibly be causing a syntax error in my JavaScript code?

<script type="text/javascript> $(document).ready(function(){ $("a.grouped_elements").fancybox( 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 600, ...