Binary calculation in pure CSS and HTML
More experiments in visualizing with checkboxes.
This time I wanted to see if I could use the checkboxes to represent an 8-bit binary number and calculate the decimal number from which inputs were checked. Using pure HTML and CSS, no JavaScript.
I'm going to do this in 2 ways. The easy way and the hard way.
The easy way #
Using CSS content, custom properties, and calc().
The one drawback to using CSS content is that it is not good for accessibility.
Since this one is easy, I can show you the CSS:
fieldset#css-content {
--b1: 0;
--b2: 0;
--b3: 0;
--b4: 0;
--b5: 0;
--b6: 0;
--b7: 0;
--b8: 0;
&:has(#bit-1:checked) {--b1: 1; }
&:has(#bit-2:checked) {--b2: 2; }
&:has(#bit-3:checked) {--b3: 4; }
&:has(#bit-4:checked) {--b4: 8; }
&:has(#bit-5:checked) {--b5: 16; }
&:has(#bit-6:checked) {--b6: 32; }
&:has(#bit-7:checked) {--b7: 64; }
&:has(#bit-8:checked) {--b8: 128; }
& output::after {
--result: calc(var(--b1) + var(--b2) + var(--b3) + var(--b4) + var(--b5) + var(--b6) + var(--b7) + var(--b8));
counter-reset: result-counter var(--result);
content: "Value: " counter(result-counter);
display: inline-block;
}
}The hard way #
The only other way I could think of doing this is by having 256 <span> elements and using a ridiculous amount of CSS to hide/show the correct number based on what inputs were checked.
And that's exactly what I did. I'm using a combination of :has() and :not(:has()) to detect every possible combination of checked inputs. Basically the CSS equivalent of brute forcing the solution.
Disclaimer: I wrote the HTML and most of the CSS for this one, but there's no way I was writing all of the central CSS logic by hand. I asked AI to output that part specifically. It would have taken me forever to do it myself.
Here it is in action:
It works and is more accessible!
This CSS is way too big to show you, so you'll need to view the page source where the CSS is both minified and post-css processed.