Given a flat list of elements (must be flat), I would like to a find an ideal combination of CSS selectors which colors only the <a>
elements which comes after a checked <input>
(checkbox), but not those who comes after some next sibling input:
(The number of items per checkbox is dynamic)
Is there a way to refactor the CSS selectors?
I’ve tried combinations with :has
or :is
but cannot come up with the right combination.
Ideally I would like a single selector for coloring on the <a>
items between the checked input and the input the comes after it in the DOM tree.
There is also a bug in the below situation (see row 4):
(It’s quite a pickle…)
* {
float: left;
user-select: none;
}
input {
clear: left;
}
input:checked ~ a,
input:checked ~ a ~ input:not(:checked) ~ :checked ~ a{
background: gold;
}
input:checked ~ a ~ input:not(:checked) ~ a {
background: none;
}
<input type=checkbox checked>
<a>🍒</a>
<a>🍒</a>
<a>🍒</a>
<input type=checkbox>
<a>🍒</a>
<a>🍒</a>
<a>🍒</a>
<a>🍒</a>
<input type=checkbox checked>
<a>🍒</a>
<input type=checkbox>
<a>🍒</a>
<a>🍒</a>
👉 I’ve created a proposal for an :until
pseudo-selector
2
Answers
Complex CSS Solution
This solution involves
position
, pseudo-elements, and:has()
. This solution will work for an unknown number of<a>
s and lines that pre-existed or dynamically added (see Example A).Example A
Details are commented in example
Simple HTML Solution
If you’re looking for the most simplest of selectors, you’ll need to isolate each group in the layout with HTML. Wrap each group in a
<label>
and assignclear: left
to eachlabel
. The last ruleset isn’t needed (see Example B).Example B
The only solution I can actually see is a "pyramid" selector using
+
until the max number of elements you know you will have.