Updating the Background Color of a Selected Checkbox in HTML

I have a straightforward question that I've been struggling to find a simple answer for. Can anyone help me with this?

Here's the checkbox code I'm working with:

<input type="checkbox">

All I want to do is change the background color when this checkbox is checked. Is there an easy method to achieve this using CSS or JS?

Answer №1

To add color to the background when a checkbox is checked, you can utilize the :checked pseudo-class along with the :after pseudo-element.

Note: If you want a fully customized checkbox with a complete background, you'll need to style the checkbox using CSS.

input[type="checkbox"]:checked {
  background: blue;
  color: white;
}

input[type="checkbox"] {
  cursor: pointer;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: 0;
  background: lightgray;
  height: 16px;
  width: 16px;
  border: 1px solid white;
  color: white;
}

input[type="checkbox"]:after {
  content: ' ';
  position: relative;
  left: 40%;
  top: 20%;
  width: 15%;
  height: 40%;
  border: solid #fff;
  border-width: 0 2px 2px 0;
  transform: rotate(50deg);
  display: none;
}

input[type="checkbox"]:checked:after {
  display: block;
}
<input type="checkbox" />

Answer №2

I recently made some updates to the code found in this reference link. Here are the essential elements you need to include:

input[type="checkbox"] {
  visibility: hidden;
}
input[type="checkbox"] + label:before {
  border: 1px solid #333;
  content: "\00a0";
  display: inline-block;
  font: 16px/1em sans-serif;
  height: 16px;
  margin: 0 .25em 0 0;
  padding: 0;
  vertical-align: top;
  width: 16px;
}
input[type="checkbox"]:checked + label:before {
  background: red;
  color: green;
  content: "\2713";
  text-align: center;
}
<input type="checkbox" id="Custom" name="Custom">
<label for="Custom">Custom Check</label>

Answer №3

Embark on this Enlightening Link

      @import url('https://fonts.googleapis.com/css?family=Roboto');
      body {
          margin: 0;
          min-height: 300px;
      }
      header {
        background-color: #f39821;
        height: 150px;
      }
      .content {
        background-color: #FFFFFF;
        max-width: 80%;
        padding: 8px 16px;
        margin-top: -56px;
        margin-right: auto;
        margin-left: auto;
        border-radius: 2px;
        box-shadow: 0 2px 2px 0 rgba(0, 0, 0, .14), 0 3px 1px -2px rgba(0, 0, 0, .2), 0 1px 5px 0 rgba(0, 0, 0, .12);
      }
      .checkbox {
        font-family: 'Roboto', sans-serif;
        margin-top: 8px;
        margin-bottom: 8px;
      }
      .checkbox__input {
        position: absolute;
        width: 0;
        height: 0;
        margin: 0;
        padding: 0;
        opacity: 0;
      }
      .checkbox__label {
        font-size: 16px;
        color: rgba(0, 0, 0, 0.87);
        position: relative;
        cursor: pointer;
        line-height: 24px;
        padding-top: 2px;
        padding-bottom: 2px;
        padding-left: 28px;
      }
      .checkbox__label:before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 18px;
        height: 18px;
        margin: 3px;
        border: 2px rgba(0, 0, 0, 0.54) solid;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        -webkit-border-radius: 3px;
        border-radius: 3px;
      }
      .checkbox__input:checked ~ .checkbox...

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

Ajax is able to send a string representation of a list rather than just the raw list itself

Utilizing jQuery to collect all the data entered on the webpage, then utilizing ajax to transmit this information to my django view. Here is the code responsible for that: var button = $("#serialise"); var JSON_content = $('#JSON_Contents') $( ...

Using jQuery.Validate to showcase the accurate panel

I have a tabbed panel setup as shown: The Student tab includes fields for StudentName and the Mark tab includes Math. Here is my Model structure: public class StudentViewModel { [Required] public string StudentName { get; set; } [Required] ...

The development of the React app will pause momentarily upon encountering a single low-severity vulnerability. To address this, you can either run `npm audit fix` to resolve it, or use `npm audit` to gain

A challenge arises while executing the command below in Visual Studio Code to develop a react app: create-react-app my-first-react-app The process halts and displays this message: found 1 low severity vulnerability run `npm audit fix` to rectify th ...

Locate the XPath for text that is within a div tag and adjacent to a span tag

I've searched, but couldn't find an exact match, so my question is about a low HTML code: <div class="column1"> <div> <div class="name"> Dynamic Name <span class="id" title="ID">Dynamic ID</span> </div> </d ...

Is there a way to verify that a form field has been completed?

Currently, I am grappling with a method to clear a field if a specific field is filled in and vice versa. This form identifies urgent care locations based on the information provided by users. The required entries include the name of the urgent care facil ...

Unable to find the matching closing parenthesis ')" before reaching the end

I've been struggling to create a regular expression that can identify strings like the ones below: var p1=@VAL([Test1Q1].[Bandwidth]) var p2=@VAL([Test1Q1].[Usages (KB)]) The criteria is to find strings starting with @VAL( and ending before the firs ...

Update the values of input fields with the class "set" in an ASP.NET loop by utilizing the map function

I have a scenario where I am looping through inputs with the costclass class using a foreach loop. The item IDs are size, cost, and costprice. The costprice is calculated as the size multiplied by the price. This calculation is done using the map method i ...

Enhance the existing User model in loopback by adding additional properties and functionalities

In my loopback app, I am looking to create a model that represents a user profile. However, the default User model provided by loopback only includes the properties: username password realm emailVerified I am wondering what is the most effective approac ...

Building an interactive chat feature with jQuery/AJAX and Pusher: A step-by-step guide

explore: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://js.pusher.com/4.4 ...

Babylon entities failing to run

Encountering a strange issue in my current project. I am working on a react application that incorporates Babylonjs for 3D rendering. While I am able to successfully load objects into the scene, I am facing a problem when attempting to create a PBR Materia ...

Mastering AngularJS - Field Population with Blinking Placeholders

I understand that AngularJS fills in fields through their model. HTML is loaded first: <input type="text" data-ng-model="data.myValue" placeholder="example"> The JavaScript code comes next: $scope.data = {}; $scope.data.myValue = 'hello my v ...

Create an interactive mechanism where one scrollbar dynamically adjusts another scrollbar and vice versa

Using the provided js-bin, how can I synchronize scrolling between the "left" div and the "right" div when using the mouse wheel? Currently, if you uncomment the code block, the scrolling behavior changes from scrolling by 100px per scroll to scrolling pi ...

SVG Height remains fixed despite aspect ratio adjustments

Using one SVG image in a div with a width of 50px results in a height of 150px in IE11. The correct dimensions should be 50px x 50px. The width is applied correctly, but the height is not. Any suggestions? .svg-cont{ width:50px } img{ max-width:100% ...

What could be the reason for the database variable being undefined in the Ajax-called PHP script?

Whenever I attempt to delete a post by clicking on .deletePost, I encounter the following issues. It appears that $mysqli is deemed as undefined, even though I employ it in a similar php script without any errors. This situation has left me perplexed, so c ...

Different methods to insert data into a database without relying on mongoose

Looking for help implementing the populate() function without using mongoose within the code snippet below: ` course.students.forEach(async (student, i) => { const s = await Student.findById(student._id); console.log(s.toObject()); // ...

Tips for efficiently storing and accessing data obtained from the "RESTBuilder" tool on the Total.js platform

After stumbling upon this informative tutorial on how to build a cryptocurrency comparison site with VueJs, I was inspired to create a single-page application using the total.js platform. My goal is to fetch the list of coins from the "coinmarketcap.com" A ...

Images displayed alongside webpage contents

I'm having trouble getting these photos to display in the same row. Any suggestions on what I should change? https://i.stack.imgur.com/EbvmR.png I've attempted using float left and other commands, but one picture continues to stay in the lower r ...

Problems with the firing of the 'deviceready' event listener in the PhoneGap application

Utilizing vs2012, I have been working on a PhoneGap application. Within this application, the following JavaScript code is being used: document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // alert("hh") ...

How can I obtain the coordinates when the mouse enters Vue?

Trying to create an animation triggered by the mouseenter event in Vue, I ran into a roadblock - obtaining the coordinates of the sections. <script setup> function fetchCoordinates(e) { const coords = { x: e.clientX, y: e.clientY } // This seems to ...

Following the modification of the Context root, the JSP page is no longer functioning as expected

Recently, I developed a JSP page within the webapp that utilizes jquery, CSS, and Angular JS. The files jquery-1.12.0.js, angular.min.js, and TableCSSCode.css are all located in the same directory as the JSP page. Initially, my application context was set ...