Modify the CSS property of a checkbox label when the checkbox is selected

Recently, I came across some interesting HTML code:

  <label>
     <input type="checkbox" value="cb_val" name="cb_name">
     my checkbox text
  </label>

After applying CSS, I successfully added a background-color to the <label> tag.

label { background-color:#333; color:#FFF; }

However, now I am facing a challenge. I want to change the background color of the label when the checkbox is checked using only CSS without relying on JavaScript. Some solutions I found use the adjacent sibling selector and assume the label appears after the checkbox, which isn't always the case.

If anyone has any ideas on how to achieve this effect with just CSS, please share your insights!

UPDATE:

Unfortunately, it seems like achieving this effect purely through CSS is not possible. I may have to resort to using JavaScript or explore alternative HTML structures to get the desired result. One suggestion was placing the checkbox absolute on top of the label for a similar visual effect. Another option is to apply the background color to both the label and the checkbox simultaneously.

Thank you for all the assistance provided!

Answer №1

If you want to achieve this using only CSS, you can do so by following these steps:

<input type="checkbox" id="cb_1" value="cb_val" name="cb_name">
<label for="cb_1">
     my checkbox text
</label>

Apply the following CSS:

label { background-color:#333; color:#FFF; }

input[type="checkbox"]:checked + label {
    background: brown;
}

Check out the implementation on JSFIDDLE

Important Note:

To maintain the desired appearance, make sure that the label comes after the checkbox in your HTML structure and adjust the styling accordingly.

You can also explore a further styled option with no absolute positioning involved in this New fiddle. It utilizes some creative CSS techniques to achieve the look you desire.

Answer №2

Applying CSS styles directly to the label itself when it is checked may not be possible, but you can style a sibling element of the checkbox instead.

Check out this JSFiddle example for more information

Here is an example of HTML code:

<label>
    <input class="check" type="checkbox" />
    <span class="label-text">Checkbox</span>
</label>

This is how you can apply CSS styling:

label {
    background: yellow;
}
label .label-text {
    background: cyan;
}
label input.check:checked + .label-text {
    background: lime;
}

You can also manipulate floats and padding to make it appear as if the checkbox is within the .label-text span.

For information on browser support regarding the sibling selector, check out http://caniuse.com/css-sel2

Alternatively, another approach mentioned is to style the label if it is a sibling of the checkbox, although the checkbox would still not be contained within the 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

How jQuery stops the submission of a form

Sample HTML Code <p><select name="status" class="form-control" id="showThisItem"> <option value=""> Select Status </option> <option value="Paid"> Paid </option> <option value="Unpa ...

Achieving successful functionality with position:relative in IE9

Having difficulty with the position: relative property in IE9. Check out this demo for reference: <div style="overflow:scroll;height:120px;"> <table id="table" width="100%"> <tr style="position:relative;background-color:#1b72a4;"> ...

Display exclusively the chosen option from the dropdown menu

I am facing an issue with the select input on my webpage. Whenever I try to print the page, it prints all the options of the select instead of just the one that is selected. Can someone please guide me on how to modify it so that only the selected option ...

Effortless content extraction between HTML tags using BeautifulSoup in Python

My Weather Data Extraction Project: I'm currently developing a webpage scraper to collect weather information. This is the progress I have made so far: import urllib.request from bs4 import BeautifulSoup # opening the webpage and storing the conten ...

conceal the offspring from the guardians, not the offspring

Could you please assist me with this situation... <li id="4331">Region <ul> <li id="4332">Asia</li> <li id="6621">Europe</li> </ul> </li> I have a query when I click on the Reg ...

"Using Vue 3 to teleport content to a specific element and swap out existing

I've successfully implemented the use of Vue 3 teleport to display elements within a div. Although teleport adds items to the specified element, it doesn't replace existing elements in the div. Is there a way to configure teleport to replace th ...

Which is better for parsing HTML - CSS or XPath selectors?

For my project, I aim to utilize lxml for parsing HTML content, as it offers support for both XPath and CSS selectors. I am currently deciding whether to bind my model properties to either CSS or XPath. I am contemplating which option would be most benefi ...

The issue with Open Sans and sans-serif fonts not rendering properly in all web browsers

I am having trouble with websites that use the Open Sans font appearing with a strange handwriting style. I'm not sure where this issue is originating from. Here are some things I have tried: Using In-Private browsing Disabling all extensions Testin ...

Troubleshooting issues with hint functionality and fullscreen mode in CodeMirror within a jQuery layout

I have integrated the codeMirror library into the UI Layout Plug-in on my website. Challenges: When using CodeMirror within the layout, the Full Screen Editing feature does not work as intended. Press F-11 to zoom in and Esc to exit full screen mode. I ...

Implementing JavaScript functionality upon page load with ASP.NET

I have come across a situation where I am trying to integrate working code (jQuery/Javascript) that makes an API call and sends data to it. The API service then responds with a success or failure message based on the data insertion into the API db. Everyth ...

the intricacies of resizing a dijit dialog

My dialog is defined as shown below: <div data-dojo-type="dijit/Dialog" id="DetailDialog" class="dijitDialog" ... I have loaded a grid inside the dialog with 10 columns. var dialog = dijit.byId("DetailDialog"); dialog.set("content", this.Details); d ...

Assign a value to the cookie based on the input from the form

I recently asked a similar question, but it seems like I missed providing some context, which is why I couldn't get it to work. My goal is to set a cookie value of a form entry when clicking on it (using the carhartl jquery plugin), but nothing happen ...

Tips for showing the database list based on the chosen value in the drop-down menu

manage_bank Hey there, I need some assistance with displaying the bank name based on the selected dropdown option. For instance, if we choose 50 records, it should display 50 records of the bank name from the database. Additionally, I want the selected v ...

Moving DOM Elements around

Objective: Looking to relocate an element within the DOM structure. Condition: Although I am familiar with using jQuery for this task, I am currently working in an environment without access to it. Therefore, I need a pure JavaScript solution. Example: ...

Endless Loading in Node.js on Google App Engine

I have deployed a standard nodejs app (free tier) using cloud shell, but when I try to access https://[ID].du.r.appspot.com/ , it keeps loading indefinitely. app.js: const express = require('express'); const path = require('path'); co ...

Looking to utilize the <pre> tag without any external CSS styles defined in a separate stylesheet?

In my current project, I am using bootstreap v3.2. I am facing an issue where I need to display fetched content from the database on a page using the <pre></pre> tags. However, the problem is that the content is being displayed with the default ...

Subnav sticks when scrolling down but becomes unresponsive on resizing

My webpage has a main header that sticks to the top of the window and a subnav fixed at the bottom. The hero image adjusts its height based on the window minus the header and subnav heights. When scrolling past the subnav, it sticks just below the main nav ...

Unlock the power of Angular pipes in window.open with URL parameters!

<div class="member-img" onclick="window.open(childEpisode.File_URL | fullPath)"> </div> The fullPath function concatenates the domain part to the relative URL stored in file_URL. However, there seems to be an issue as it i ...

Does using .detach() eliminate any events?

I have a DIV that is filled with various content, and I am using the detach() and after() functions to move it around within the document. Before moving the DIV, I attach click events to the checkboxes inside it using the bind() function. Everything seems ...

Center a single div vertically within a parent div by utilizing a fluid layout

Attempting to align text elements within a responsive layout presents challenges due to the fluid nature of <div> sizes. I recently discovered a fantastic method for horizontally and vertically centering a child <div> inside its parent <div ...