Pure CSS Toggle (Change) Color of HTML Element


CSS only toggle the color of HTML DOM element. No JavaScript required. See demo first. Please click the following text to toggle the color of the div element:



My color will be toggled

The color is black in the beginning, if you click on the text, the color will be changed to red. If you click again, the color will be changed back to black, and so on.

This demo uses the technique of CSS toggling in [1]. There are three main HTML elements in the demo:

<label for="element-toggle">click me to toggle color</label>
<input id="element-toggle" type="checkbox" />

<div id="toggled-element">My color will be toggled</div>
  1. A visible HTML label element
  2. A invisible HTML input checkbox element, referenced by the above label element via for attribute.
  3. The element to be width-toggled. It is a div element in the demo.

When users click on the visible label element, the invisible input checkbox element becomes checked/unchecked by the click. Then the following CSS rules are used to toggle the width of the element according to whether the checkbox is checked or not.

label[for=element-toggle] {
  cursor: pointer;
  color: blue;
}
#element-toggle {
  display: none;
}
#toggled-element {
  padding: 1rem;
}
#element-toggle:checked ~ #toggled-element {
  color: red;
}

There are four rules in above CSS code. The last rule is the most important part in this trick. It says if the element with id=element-toggle (i.e., the input checkbox) is checked, the color of adjacent element id=toggled-element (div element in this case) becomes red. If the input checkbox is not checked, this rule is not applied to the div element, which makes the div element original color. The last CSS rule toggles the color of div according to whether the checkbox is checked or not.


Tested on:

  • Chromium Version 63.0.3239.84 (Official Build) Built on Ubuntu , running on Ubuntu 17.10 (64-bit)

References:

[1]Pure CSS Toggle (Show/Hide) HTML Element
[2]Pure CSS Toggle Centered Element Width