I'm creating a simply show more
solution for a page where there are n
text elements that need toggling between show
and hide
. n
is dynamic and not fixed.
For the purposes of this question, I'm exploring non-JS, CSS-only solutions.
It's possible to achieve a show
and hide
toggle functionality for a single element via CSS (solution below). But how does one extend it to n
elements? Would be great to get an illustrative, working answer.
How I would do it in a single text element case:
#textarea {
/* hide by default: */
display: none;
}
/* when the checkbox is checked, show the neighbouring #textarea element: */
#textAreaToggle:checked + #textarea {
display: block;
}
/* position the checkbox off-screen: */
input[type="checkbox"] {
position: absolute;
left: -1000px;
}
/* Aesthetics only, adjust to taste: */
label {
display: block;
}
/* when the checkbox is unchecked (its default state) show the text
'Show ' in the label element: */
#textAreaToggle + #textarea + label::before {
content: 'Show ';
}
/* when the checkbox is checked 'Hide ' in the label element; the
general-sibling combinator '~' is required for a bug in Chrome: */
#textAreaToggle:checked ~ #textarea + label::before {
content: 'Hide ';
}
<input id="textAreaToggle" type="checkbox" /><p id="textarea">This is hidden textarea, that needs to be shown</p><label for="textAreaToggle">textarea</label>
This single-case solution is based on this answer, and it's tried and tested. You can run the code snippet to see for yourself.
But I'm struggling to generalize it for n
text elements on a single page (in a CSS-only setting), thus this question.