Mark VY
Mark VY

Reputation: 1671

Hide table row based on checkbox in pure CSS

A bit of backstory, for those who care: some time ago I stumbled across this: https://medium.com/front-end-hacking/how-it-feels-to-learn-javascript-in-2017-a934b801fbe, and in particular, this: https://brlewis.github.io/2017/planets.html

And today I thought: CSS is perfectly capable of hiding things based on the state of checkboxes, which would achieve pretty much the same effect. The only trouble is, I have no idea whether CSS selectors are flexible enough to select the right table rows.

So, my question is this: given some HTML resembling this:

<label><input type=checkbox id=rock> Terrestrial</label>
<label><input type=checkbox id=gas> Gas Giant</label>
<label><input type=checkbox id=ice> Ice Giant</label>
<table>
<tr class=rock><td>whatever
<tr class=ice><td>whatever
... and so one...
</table>

Can we do something like this?

magic ~ > :checked ~ tr {display: none}

Upvotes: 2

Views: 1283

Answers (1)

Naren Murali
Naren Murali

Reputation: 56410

Final Answer:

Here is my mockup of what you are trying to do. By the way Nice Question!!!

input#rock:checked ~ table tr.rock {display: block}

input#gas:checked ~ table tr.gas {display: block}

input#ice:checked ~ table tr.ice {display: block}

input:checked ~ table tr {display:none}
<input type=checkbox id=rock><label> Terrestrial</label>
<input type=checkbox id=gas><label> Gas Giant</label>
<input type=checkbox id=ice><label> Ice Giant</label>
<table>
<tr class=rock><td>whatever for rock</td></tr>
<tr class=ice><td>whatever for ice</td></tr>
<tr class=gas><td>whatever for gas</td></tr>
</table>

Old Answer:

If you seperate the label and the checkbox it can be achieved like so!

input:checked ~ table tr {display: none}
<input type=checkbox id=rock checked><label> Terrestrial</label>
<input type=checkbox id=gas><label> Gas Giant</label>
<input type=checkbox id=ice><label> Ice Giant</label>
<table>
<tr class=rock><td>whatever</td></tr>
<tr class=ice><td>whatever</td></tr>
</table>

Upvotes: 4

Related Questions