Obtaining the checkbox status from a location other than immediately following the input by CSS alone

I am currently designing a custom checkbox feature where clicking on the label text will toggle the state and display or hide certain text based on the checkbox state, all achieved solely through CSS. The HTML code I have written for this purpose is as follows:

<input type="checkbox" name="check"> <span class="label-text">Item Two</span>
    <div class="elements">
      <div class="is_checked">
          Checkbox is checked
      </div>
      <div class="is_not_checked">
          Checkbox is not checked
      </div>

Although this setup is functional, I am unsatisfied with how the checkbox changes its state when interacting with the text element. Moving the elements out of the label removed this issue but also made it impossible to access the checkbox state. I attempted the following solution without success:

(label > input[type="checkbox"]:checked) ~ .elements .is_not_checked{
    display: none;
}

This approach failed to even hide the text. How can one effectively access the state of a hidden checkbox within another element, in this case, a label, using only CSS?

Answer №1

Utilize HTML to create a connection between the label and the checkbox, allowing a click on the label to toggle the state. By leveraging the checked state of the checkbox and the sibling selector, it is possible to toggle the elements.

<style>
    input[type=checkbox] {
        display: none;
    }
    input[type="checkbox"] + label:before {
        content: "+";
        width: 1em;
        height: 1em;
        display: inline-block;
        margin-right: 5px;
    }
    input[type="checkbox"]:checked + label:before {
        content: "-";
    }
    input[type=checkbox]:checked ~ .elements div.checked,
    input[type=checkbox]:not(:checked) ~ .elements div.unchecked {
        display: block;
    }
    input[type=checkbox]:checked ~ .elements div.unchecked,
    input[type=checkbox]:not(:checked) ~ .elements div.checked {
        display: none;
    }
</style>

<input type="checkbox" id="check" name="check">
<label for="check">My Item</label>
<div class="elements">
    <div class="checked">Checkbox is checked.</div>
    <div class="unchecked">Checkbox is NOT checked.</div>
</div>

Answer №2

I have made adjustments to the HTML layout by switching out label with div class="label".

Instead of utilizing display: none, I have hidden the checkbox using opacity. This allows for better control over its size and position.

.label {
  position: relative;
  display: inline-block;
}

input[type="checkbox"] {
  opacity: 0;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
}

input[type="checkbox"]+.label-text:before {
  content: "+";
  width: 1em;
  height: 1em;
  display: inline-block;
  margin-right: 5px;
}

input[type="checkbox"]:checked+.label-text:before {
  content: "-";
}

input[type="checkbox"]:checked~.elements .is_not_checked {
  display: none;
}

input[type="checkbox"]:not(:checked)~.elements .is_checked {
  display: none;
}
<div class="label">
  <input type="checkbox" name="check">
  <span class="label-text">Item Two</span>

  <div class="elements">
    <div class="is_checked">
      Checkbox is checked
    </div>
    <div class="is_not_checked">
      Checkbox is not checked
    </div>
  </div>
</div>

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 correct way to apply background-position percentage in this situation?

This problem has got me at my wit's end. Imagine a series of divs lined up horizontally. Each one is sized as a percentage of the total width, but that total width is unknown. For instance: --------------------------------- | | | ...

Is it possible that JavaScript isn't functioning properly?

My current issue involves echoing JavaScript from a PHP file to an HTML page using AJAX. Strangely, the JavaScript does not run when dynamically echoed, even though it appears in the Inspect Element tool. On the other hand, purely textual content echoes su ...

Creating a stylish button using Bootstrap in an MVC Core HTML Tag Helper

I recently scaffolded a table in MVC and created a view. I would like to customize the Edit button by changing it to a blue Bootstrap button. How can I accomplish this? Existing Code: <td> <a asp-action="Edit" asp-route-id="@ ...

Demonstrate a array of values at varying angles within a circle using the functionalities of HTML5 canvas

Looking to utilize HTML5 Canvas and Javascript for a project where I need to showcase various values (depicted by dots possibly) at different angles within a circle. For example, data could include: val 34% @ 0°, val 54% @ 12°, val 23% @ 70°, a ...

What is the best way to ensure that my image completely occupies the div?

I am facing a challenge in creating a hero image that would completely fill the div on my webpage. Despite setting the width and height to 100%, the image seems to only occupy half of the space. Check out the CSS and HTML code snippet here. div.hero{ ...

Submitting a form from outside the form using a button in HTML: A step-by-step guide

I'm looking to submit a form using Angular on the functions next() and saveStep(). I'm unable to place next() and saveStep() within the form itself. I have set up my ng-click for next() and saveStep() below the form. When I submit the form fro ...

Accessing a form control's class in code behind using asp.net

<form id="form1" runat="server" role="form" class="form-horizontal"> Is there a way to modify the class of a control in the code behind? I want to update its value. Appreciate any help! ...

Tips for submitting an e-mail through an HTML form with the help of Node.js and Gulp

Today, I've been tackling the challenge of creating an HTML contact form that can send an email using Node.js and Gulp. However, I'm struggling to find a solution. Using a relative path to a simple .PHP file doesn't seem to be working, so it ...

Angular and Bootstrap combined to create a versatile navigation bar with a collapsible sidebar feature

Currently, I am in the process of developing a progressive web app using Angular and Bootstrap. One of the main challenges I am facing is implementing a navbar that not only looks great on desktop but also on mobile devices. So far, I am satisfied with my ...

Tips on boosting CSS specificity in Material-UI's makeStyle for styled components in order to successfully override the root style

As a newcomer in the world of React, I am attempting to utilize MUI makeStyles to customize the existing styles. However, I have encountered an issue where setting fontWeight to 'bold' does not seem to work, even when using !important. Any sugges ...

What are some techniques I can use to ensure my image grid is responsive in html/css?

If you want to check out the website, you can visit . The main goal is to create an image grid for a portfolio. It appears really nice on a 1080p screen, but anything below that seems messy and unorganized. Any assistance or suggestions on how to improve ...

Issue with CSS rendering in Internet Explorer

Although my website appears perfectly in Firefox, the entire style sheet doesn't seem to load properly in IE 7. It's only displaying certain styles. Any assistance on this issue would be greatly appreciated! ...

What is the best way to incorporate the .top offset into a div's height calculation?

Looking to enhance the aesthetic of this blog by adjusting the height of the #content div to match that of the last article. This will allow the background image to repeat seamlessly along the vertical axis. I attempted the following code: $(document).re ...

Is there a possible method to obtain a smartphone number from a website?

Seeking a solution to retrieve the phone number of a device using HTML 5, JavaScript, or similar technology. Recently, I successfully obtained the coordinates of the device by incorporating the following JavaScript code: <!DOCTYPE html> <html> ...

Managing various swipe interactions using HTML and JavaScript/jQuery

I'm in the process of creating a mobile multiplayer game using HTML5 and Javascript. The jQuery Plugin "touchwipe" is utilized to manage swipe events in various divs like this: $('#play1').touchwipe({ wipeLeft: function(){ if ...

Content is not centered with Bootstrap's flexbox

The alignment of content is not centered using bootstrap flex <div class="d-flex flex-row bd-highlight mb-3"> <div class="p-2 bd-highlight text-left"><i class="fa fa-chevron-left" aria-hidden="true"></i></div> <div cla ...

Using PHP with Slim PHP Framework to dynamically include CSS files in the header of a document

I have developed a sleek application featuring a login form, dashboard, registration page, and account page. Each of these pages has its own unique route. To maintain consistency across all pages, I have included a shared header and footer by inserting < ...

Conceal button divider on pager in Jqgrid

Within my grid setup, there are 3 buttons placed in the pager section: 'Refresh', 'Constution', and 'Developed'. These buttons are separated by two vertical navSeparators. Upon grid load, the 'Developed' button is hi ...

When an image is added, it will display against a backdrop of pure white

Hey there, I have a question regarding an image on my website. I removed the background using PowerPoint, but when I upload it, there is still a white background around it. Even changing the background color doesn't remove the white outline. Any tips ...

What is the best way to keep the menu bar in place as you scroll?

Can someone help me figure out how to keep the menu bar fixed at the top of the page when the user scrolls down? I've tried various methods but haven't had any luck. Any assistance would be greatly appreciated. Here is the CSS code: And here is ...