Tips on how to format a checkbox that is contained within a label element

My typical approach for setting up a checkbox involves using the code below:

<input ....>
<label for="...">Lorem ipsum</label>

I usually style the label to mimic a checkbox when checked or unchecked like this:

input label{....}
input::checked label{....}

However, due to a Wordpress plugin, I am now required to use this syntax:

<label>....
    <input....>
</label>

Since CSS cannot navigate the DOM in this case, my usual CSS method is not effective.

Any alternative suggestions? Maybe jQuery would work here? Or is there a CSS solution that I haven't considered?

Answer №1

From what I know, CSS cannot traverse the DOM to achieve this task, as you mentioned earlier.
Regrettably, label:checked does not work either.

Therefore, a JS/jQuery solution is required:

$(function() {
  $(':checkbox').on('change', function() {
    $(this).closest('label').toggleClass('active', $(this).is(':checked') );
  });
});
label {
  border: 2px solid red;
}
.active {
  border-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label>
  <input type="checkbox" />
</label>

In cases where the label precedes the input element... In such scenarios, it is recommended to use the for attribute to ensure that the label is associated with the correct input field. The code would look like this:

$(function() {
  $(':checkbox').on('change', function() {
    $('label[for='+ $(this).attr('id') + ']' ).toggleClass('active', $(this).is(':checked') );
  });
});
label {
  border: 2px solid red;
}
.active {
  border-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label for="idforcheckbox">This is the label</label>
<input id="idforcheckbox" type="checkbox" />

Answer №2

Yes, incorporating JavaScript is necessary for this functionality. CSS alone cannot manipulate parent elements. Consider the following jQuery snippet:

$(document).on('click','input[type="checkbox"]',function() {
  if(!$(this).is(':checked')) {
    $(this).parent().removeClass('checked');
  } else {
    $(this).parent().addClass('checked');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox">
</label>

Answer №3

This technique can now be achieved using CSS alone:

label:has(input:checked) {
  /* apply styles to labels containing a checked input */
}

Apply the above selector to format the "checked" input(s).

To style the "unchecked" input(s), target the label element instead.

label {
  /* apply styles to labels containing an unchecked input */
}

For more specific targeting, consider using:

label:not(:has(input:checked)) {
  /* apply styles to labels containing an unchecked input */
}

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

Designing the Irish flag solely with HTML and CSS: a step-by-step guide

I have successfully created the Indian flag using HTML and CSS, with the exception of the Ashok Chakra. Now, I am looking to create the Irish flag which features a vertical tricolor design, unlike the horizontal tricolor layout of the Indian flag. Can anyo ...

Does setting white-space:nowrap enlarge the div?

My CSS code for div .name sets the width to 75% to truncate text if it doesn't fit. However, resizing the window causes the text to remain the same size and my entire website structure falls apart. This is the HTML code snippet: <tr> <t ...

Is it possible for me to customize the CSS of the masterpage for a specific aspx file?

Recently, I completed a website that was almost ready to be published. However, my client now wants to add a new page with similar content as the main masterpage (including the logo, menu, and a few buttons), but with some changes in colors and background ...

IE disregard min-height property of flex container

After researching, it appears that using the standardized flex terms should work with IE10/IE11. I have a container div with 2 child divs. Both child divs are smaller than 400px, so there should always be enough space for the justify-content: space-betwe ...

PHP persistent forms dropdowns and checkbox selection

I am currently working on a PHP form and I am facing an issue with the drop-down boxes and checkboxes. I want them to stay filled even if I don't select something, maintaining the previously entered details while leaving the unfilled parts empty. I ha ...

Implemented sub navigation within off canvas navigation, allowing sub menu headers and menus to remain visible even when the main menu is closed

I've been working on customizing an existing off-canvas design and I've run into a roadblock. I added submenus, but they're displaying even when the menu is closed. I suspect it's a positioning problem, but despite spending several days ...

Experience the smooth CSS3 transition effects on iOS devices such as iPhones and iPads. Elevate the appearance of DOM objects with

I have a basic image contained within a div tag. I use JavaScript to add a transition effect to the div element: <div style="transition: opacity 0.8s linear; opacity: 0.5;"><img src="..." /></div> At the end of the transition duration ...

How to delete the Location Hash from a URL with JavaScript or jQuery

I have encountered a unique issue not addressed in previous discussions. When the destination id is on a different page, I am experiencing difficulty removing #url. My Approach : On two HTML pages - index.html & about.html, I have displayed various menu ...

Troubleshooting border-radius problem with Firefox-CSS for the pseudo-element "before"

I'm encountering an issue with a card-element in bootstrap-4 that has a front and back side. When hovered over, the back side is displayed. To achieve a "folded corner effect," I'm using a pseudo-element(:before) on the front of the card. This me ...

The JSSOR Slider encounters issues when trying to display dynamic content

I've created a basic HTM page and I'm attempting to incorporate the JSSOR Slider. Unfortunately, it doesn't seem to be functioning properly. Despite checking the console for errors, nothing seems to be out of place. When clicking on the arro ...

Customize bullet list icons to adjust in size based on content using css

In my CMS project, the CMS team has a special requirement regarding unordered and ordered lists. They want the size of the bullet list icon to adjust according to the text content within the list. The image below shows the default design of a list item: ...

Transcribe characteristics back into an array

I am looking to save an array into a table row attribute initially and then attempt to convert those attributes back into an array format. var arr_Rates = new Array(); arr_Rates.push({Single:"value",Double: "value"}); $('table tr').attr("arr_Rat ...

Executing JavaScript in Rails after dynamically adding content through AJAX

Looking for advice on integrating JavaScript functions into a Rails app that are triggered on elements added to the page post-load via AJAX. I've encountered issues where if I include the code in create.js.erb, the event fires twice. However, removing ...

How do you determine the dimensions of a background image?

My div is a perfect square, measuring 200 pixels by 200 pixels. The background image I've chosen to use is larger at 500 pixels by 500 pixels. I'm searching for a method to ensure that the entire background image fits neatly within the confines ...

I am interested in running JavaScript code on a page that has been loaded through AJAX

I am struggling to execute the Javascript loaded within an ajax page. Here is the link to my loaded ajax page: https://jsfiddle.net/4dsbry7j/ JS : var xmlhttp = new XMLHttpRequest(); var url = "http://localhost/ajax/find2.php"; xmlhttp.onreadystatechang ...

"Assigning an array as a value to an object key when detecting duplicates in a

Let's assume the table I'm iterating through looks like this: https://i.stack.imgur.com/HAPrJ.png I want to convert each unique value in the second column into an object, where one of the keys will hold all values from corresponding rows. Here& ...

What is the best way to create a transparent effect over a solid color using CSS in the following situation?

I have been using the spinner on this website "". Specifically, I am referring to the third one in the first row. When I apply it to my system, a solid color appears in the center of the circle. However, I want to make it transparent, but when I attempt ...

What is causing the Load More feature in jQuery to malfunction?

Attempting to create a basic "load more" feature using jquery. The concept is to mimic the functionality of traditional pagination where clicking loads additional posts from the database. Below is the javascript code: $(function(){ var count = 0; var ...

What is the process for including information in an object?

Having an API that can handle both single data and bulk data requests, I am able to send a single data request using the following code: var contactId = 123; var url = "www.abc.com"; var companyName = "ABC"; var compLink = "/abc/123/link"; var randomKey = ...

Tips for wrapping text without breaking the input field onto a new line

I'm struggling to create the following UI design. [text1] [inputBox1] [text2] [inputBox2] [text3] [inputBox3] The length of text1, text2, and text3 can vary. So, as the length of text increases, their width should also increase, causing the input bo ...