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

Ways to dynamically adjust the color of the text font?

Below is the XML content: span style="background-color: rgb(255, 255, 0); The background color mentioned here is linked to my Java code. Since this color changes dynamically, it varies in each report. My inquiry is about how to incorporate this color in ...

Basic event listener function, functional in CodePen but not operating in Chrome web browser

I'm experiencing an issue where event listener functions are not working on my browser (Chrome), but they work fine on CodePen. I've been troubleshooting this for about 2 hours, and I'm seeking some insights. Can anyone help? CodePen Link: ...

The process of dynamically inserting input types into a <td> element using the innerHTML tag is not functioning properly in Internet Explorer

I am facing an issue with dynamically placing input types within a <td> tag - the innerHTML() method is not functioning properly in Internet Explorer, although it works fine in Mozilla. This is how I am inserting the input types using JavaScript, wi ...

Are the site-wide navigation links working on one page but not the other?

Currently, I am in the process of constructing a website on rails and have successfully integrated a site-wide navigation bar to display on all pages. However, an issue has arisen where the navbar is visible on both pages, yet the links and hover effects a ...

Optimal Approach for Managing ASP.NET Ajax Modal with MouseOver - Data Retrieval Only Upon Request

I'm interested in developing a modal popup that dynamically fetches the data inside it upon mouseover, instead of preloading all the data beforehand. Are there any scripts or frameworks available that would simplify this task? ...

Encountered an error while using NPM Bootstrap Carousel: Uncaught TypeError - Super expression must be either null or a function

Currently using the NPM build of Bootstrap (with Gulp) for a custom WordPress theme, and I seem to be facing some issues. While I am new to Bootstrap, I have previous experience with WordPress and Gulp (primarily with Foundation). Below is how I am includ ...

Using both Bing and Google geolocation services due to compatibility with Internet Explorer

Hey there! I'm currently working on implementing geolocation functionality into my project, and it's been smooth sailing except for one hiccup - Internet Explorer doesn't seem to play nice with Google Maps and prefers Bing instead. Has anyon ...

Pass data to child component in react

I have a parameterized component that can take a value of true or false, and I'm using console.log to verify it. console.log(isContract); //can be true or false Now, I need to pass this value through a form to render another component. This is the p ...

Difficulty Sorting Dates in Material UI DataGrid

I have a DataGrid in Material UI, and one of my columns displays dates. Following the guidance from the Material UI documentation, I have set the type to "date" in the column array: { field: "submittedAt", headerName: "Submitted", minWidth: 150, flex: 2, t ...

Add more functionality to the server.js script

I have the server.js file, which serves as the entry point for my Node application and is responsible for invoking three different functions (these functions are only called once when the server is up, such as creating child processes, validation, etc), wh ...

Tips for placing modal box in the exact desired position upon loading

I've been searching for a solution on how to dynamically calculate the position of each image loaded in a Twitter modal box and place the box underneath a custom toolbar element I have created. The situation is depicted in the image. The height of the ...

having difficulty showing the primary content page

I'm having trouble displaying a header, side navigation bar, and main content on my page with the code below. Instead of showing anything, I keep getting a parse error: unexpected end of file. What could be causing this issue? <!doctype html> ...

Disable reloading when submitting and reset input fields after submission

I am working on developing a website where users can post things and comments without the need to refresh the page. I have encountered some issues while implementing this feature and need some assistance with it. My goal is to allow users to submit comment ...

What is the jquery alternative to the PHP 'if IP equals' condition?

I am curious to know if the following PHP 'if' conditions can be achieved in jquery or JavaScript, with a preference for jquery. if ($_SERVER['REMOTE_ADDR'] != '123.99.55.616') { // public doingness } if ($ ...

What could be causing my dropdown links to malfunction on the desktop version?

I've been developing a responsive website and encountering an issue. In desktop view, the icon on the far right (known as "dropdown-btn") is supposed to activate a dropdown menu with contact links. However, for some unknown reason, the links are not f ...

Tips for toggling a menu by clicking a link

I have a Navbar component with a hamburger menu. When the hamburger menu is clicked, I want to display the menu component, which is separate. To achieve this, I passed data through props and made it work. Now, I want the menu to close when clicking outsi ...

Error in AngularJS when attempting to use an expression as a parameter for a function, resulting in a syntax parse

Encountering an issue while attempting to parse this code snippet. I need to pass an expression as a parameter in the ng-click function, but it's not allowing me to do so. If I don't use an expression, then clicking on the album image will clear ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

Yii2 HTML helper input must be marked as required

This is the form I have generated using the HTML helper: <div class="row"> <div class='form-group col-lg-6 col-sm-6'> <?= HTML::label('Name:','PropertyContactsNew',['class' => 'control-l ...

Retrieve an item fetched from the database using Javascript in MVC4 framework

How can I access the properties of an object returned from a database using JavaScript? This JavaScript function is invoked: function searchUser() { var userName = document.getElementById('UserName').value $.post("SearchForUser", { user ...