Global boolean with checkbox checked and general sibling combinator

suggest change

With the ~ selector, you can easily implement a global accessible boolean without using JavaScript.

Add boolean as a checkbox

To the very beginning of your document, add as much booleans as you want with a unique id and the hidden attribute set:

<input type="checkbox" id="sidebarShown" hidden />
<input type="checkbox" id="darkThemeUsed" hidden />

<!-- here begins actual content, for example: -->
<div id="container">
    <div id="sidebar">
        <!-- Menu, Search, ... -->
    </div>

    <!-- Some more content ... -->
</div>

<div id="footer">
    <!-- ... -->
</div>

Change the boolean’s value

You can toggle the boolean by adding a label with the for attribute set:

<label for="sidebarShown">Show/Hide the sidebar!</label>

Accessing boolean value with CSS

The normal selector (like .color-red) specifies the default properties. They can be overridden by following true / false selectors:

/* true: */
<checkbox>:checked ~ [sibling of checkbox & parent of target] <target>

/* false: */
<checkbox>:not(:checked) ~ [sibling of checkbox & parent of target] <target>

Note that <checkbox>, [sibling ...] and <target> should be replaced by the proper selectors. [sibling ...] can be a specific selector, (often if you’re lazy) simply \* or nothing if the target is already a sibling of the checkbox.

Examples for the above HTML structure would be:

#sidebarShown:checked ~ #container #sidebar {
    margin-left: 300px;
}

#darkThemeUsed:checked ~ #container,
#darkThemeUsed:checked ~ #footer {
    background: #333;
}

In action

See this fiddle for a implementation of these global booleans.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents