The problem#
A common use of JavaScript is to change which content is displayed on a web page. In some simple cases this can actually be done without JavaScript. While there's some older articles on how to do this, some newer HTML/CSS features can help.
The solution#
The simplest case is the <details>
tag which allows
showing a foldable section without even requiring any CSS. But for more
complicated cases, variations on the "Checkbox Hack"
can allow CSS to express more complicated rules about what to show/hide.
The examples in that article all rely on the content being revealed
being a sibling of the <input>
element defining the checkbox. That's
less restrictive than it sounds because the <label>
element that's
the actual visible part of the checkbox can be placed anywhere. But
even that restriction can be loosened using :has()
as shown
in this example simplified from the HTML/CSS used by my previous
post:
<div class="filters">
<label>
<input type="checkbox" id="show_completed">
Show Completed Tasks
</label>
</div>
<div class="todo_list">
<ul>
<li class="completed">some task</li>
</ul>
</div>
.completed {
display: none;
}
.filters:has(#show_completed:checked) ~ .todo_list .completed {
display: list-item;
}