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

What is the best method for ensuring that cheese rises to the top?

Is there a way to increase the value of the variable cheese? I suspect it has something to do with how the variable cheese is defined each time the JavaScript is activated, but I'm not sure how to go about it. Can you offer some guidance on this? & ...

An error with rendering in Internet Explorer 8

When I hide a td in a table by setting its display to none, the table does not resize correctly when using IE8. If I have a table and want to remove an entire column, I might try something like this: $("th:first, th:last, tr td:first-child, tr td:last-ch ...

Issue "The only acceptable numeric escape in strict mode is '' for styled elements in Material-UI (MUI)"

Attempting to utilize the numeric quote for quotation marks, I encountered an issue: 'The sole legitimate numeric escape in strict mode is '\0` The snippet of code causing the problem can be seen below: export const Title = styled(Typogra ...

How to Align Items Horizontally in React Material UI Grid for Containers of Varying Item Counts

I've been utilizing the React Material UI Grid System to arrange my elements on the page, which utilizes flexboxes internally. While everything is functioning properly, I'm struggling with horizontally aligning items in containers that have vary ...

Issue with triggering (keyup.enter) in Angular 8 for readonly HTML input elements

My goal is to execute a function when the user presses Enter. By setting this input as readonly, my intention is to prevent the user from changing the value once it has been entered. The value will be populated from a popup triggered by the click attribut ...

Updating image source dynamically with Flask

I am currently developing a face detection application using Flask. I aim to have the detected faces displayed in real-time on the HTML page. For the JavaScript aspect, I am utilizing getUserMedia to live stream camera images from the client to the server ...

Issues following compilation with npm run prod

I am currently working on a small website using Laravel and Tailwind CSS on shared hosting. While I am able to use a command line tool on the host, I have encountered an issue. In my local environment, Tailwind works perfectly fine. However, after running ...

Ways to condense a text by using dots in the middle portion of it

How can I dynamically shorten the text within a container that varies in width? The goal is to replace the strings between the first and last words with dots so that it fits within the container. For example, Sydney - ... - Quito. It should only replace wh ...

Is it possible to create varied background shades in CSS3 without relying on images?

Check out this fiddle: http://jsfiddle.net/dzAJp All the divs are styled with a light blue background color using the background-color CSS property instead of background-image. I want to darken the second div slightly by combining its current background ...

Struggling with textpath SVG elements in jQuery

Currently, I am implementing SVG in my project and aiming to apply the toggleClass function using jQuery on the textpath elements upon clicking. My initial plan was: $("text#names > textpath").click(function() { $(this).toggleClass("newClass"); }) ...

Capybara - Navigating a page by clicking on a link related to another value

I'm currently facing a challenge in locating and selecting a particular link on a web page. All links within an HTML table contain the term 'Edit' (it's a link for editing configuration settings). However, the exact link changes depend ...

Turn off the special treatment of the "class" attribute

The Background: When using BeautifulSoup to parse HTML, the attribute class is considered a multi-valued attribute and is treated differently: It's important to remember that a single tag can have multiple values for its "class" attribute. When se ...

Unable to define a range for the hr element using the nth-of-type selector

Why isn't the hr element from the 1st to the 3rd hour red as specified in the CSS code below? hr:nth-of-type(n+1):nth-of-type(-n+3){ background:red; } <!DOCTYPE html> <html> <head> </head> <body> <hr /> <p>T ...

How can I display data saved from step 2 in a multi-step form with 4 steps, when I return from step 3 to step 2?

Let's consider this scenario: Imagine the user is at step 2 and types their name into <input type="text" class="form-control input-xl" ngModel name="firstName"> They proceed to step 3 but then decide to return to step 2. The information entere ...

Adding border color and width to an ion-avatar element can be achieved by using CSS properties

I've been struggling to add a border color and width to an ion-avatar element in Ionic 4. I've attempted to use various CSS3 code snippets, but nothing seems to work. This is what I have tried: .ion-avatar img{ width: 90px !important; h ...

Troubleshooting image resolution issues in ASP web application (using C#)

I've been working on developing an asp web application that requires users to register details of a person, including uploading an image. The file name of the details/image are stored in a SQL database with the image filename saved in an NVARCHAR colu ...

Tips for overlaying text onto a MaterialUI icon

https://i.stack.imgur.com/cFr5Y.pngI am currently working on a project that requires me to overlay a number on top of an icon. Specifically, I am utilizing the MaterialUI ModeComment icon and attempting to display text over it. Despite trying the following ...

Prevent selection on all elements except for input fields with the type of text

I am facing a challenge where I need to prevent selection on a website page for everything except input[type=text] elements. The answer provided in this accepted response to a similar query almost solves the issue. However, it doesn't stop users from ...

Which element to use for creating a color palette - <img>, <div>, or <canvas>?

I am currently in the process of developing a color-picker component using HTML, CSS, and Javascript. One key question that I have is how to best implement a color palette similar to the one below: Putting aside browser compatibility concerns with IE8 or ...

Use PHP to highlight the row that has been selected in an HTML table

I am currently working on a project where I have styled multiple HTML tables on my website using alternating gray and white bands. Now, my goal is to highlight the selected row in a darker shade of gray. I have experimented with various solutions, and the ...