Toggle checkbox message on click in pure CSS

Mateusz -

We can forget about toggle method in JavaScript or jQuery and do the same in pure CSS.

<!-- -->
<div class="checkbox-wrapper">
   <input type="checkbox" id="agree" />
   <label for="agree">Delete data</label>
   <span>Warning! All your data will be deleted.</span>
</div>
<!-- -->

We have our simple form. If the user clicks our checkbox we want to display him an additional warning, a message. We can achieve that in pure CSS.

/* */
   span {
     display: none;
     color: red;
   }

   .checkbox-wrapper:has(input[type="checkbox"]:checked) span {
     display: block;
   }
/* */

What we are telling our browser? If checkbox-wrapper HAS any checkbox that is checked, please find inside checkbox-wrapper a span and display it to the user.

Summary

Combining pseudo class :has with inputs gives us another simple trick to use pure CSS to toggle messages, instead of using JavaScript code.