Wednesday, October 03, 2018

Maintain boolean state in CSS? Use label and for with a hidden checkbox.

Kind of obvious, but I wanted to make it clear and to remember it for the future. You want to make something appear or not based on a toggle button, usually done by adding a click handler on an element with some code to determine what happens. But you can do it with HTML and CSS only by using the label element pointing to a hidden checkbox with its for attribute. Example:

   I have been toggled!

Here is the HTML and CSS for it:
<style>
     /*  you have to use a caption element instead of a control element inside the label, so a button would not work and we use a span to look like a button */
     .button {
       border: solid 1px gray;
       padding: 5px;
       display: inline-block;
       user-select: none;
       cursor: pointer;
     }
 
     /* the element after the unchecked checkbox is visible or not based on the status of the checkbox */
     #chkState + span { display: none; }
     #chkState:checked + span { display: inline-block; }
  </style>
  <label for="chkState">
    <span class="button">Toggle me!</span>
  </label>
  &nbsp;&nbsp;&nbsp;
  <input type="checkbox" style="display:none" id="chkState" />
  <span>I have been toggled!</span>

Update: You might want to use an anchor instead of a span, as browsers and special software will interpret it as a clickable, but not input control.

Update: You can, in fact, instruct the browser to ignore click events on a button by styling it with pointer-events: none;, however that doesn't stop keyboard events, so one could navigate to the button using keys and press Space or Enter and it wouldn't work. Similarly one could try to add an overlay over the button and it still wouldn't work for the same reason, but that's already besides the point. Anyway, either of these solutions would disable the visual style of the clicked button and web sites usually do not use the default button style anyway.

There is one reason why you should not use this, though, and that is usability. I don't know enough about it, though. In theory, a label should be interpreted the same as the checkbox by software for people with disabilities.

0 comments: