Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group list of elements by arbitrary attribute with CSS [duplicate]

HTML:

<ul>
  <li attribute_name='a'>Test</li>
  <li attribute_name='a'>Test</li>
  <li attribute_name='b'>Test</li>
  <li attribute_name='b'>Test</li>
</ul>

I would like to select only the third <li> in this example. The attribute name is fixed, but its value is dynamic and not known in advance. The number of <li>s is also dynamic. Can this be done in pure CSS?


1 Answers

Whether there is a solution to this really depends on your markup.

Because selectors are mostly static and do not have variables, there is no way using a selector to match any element with a specific attribute value based on another element (or the lack thereof) with the same attribute value, without knowing the value in advance. If the possible values for this attribute cannot be determined, then there is no pure CSS solution.

If only a finite set of values exists for this attribute and you knew these values in advance, you could write a selector for each possible value, but you would need to hardcode every one of those values. Such a selector would be constructed using the :not() pseudo-class in conjunction with an adjacent sibling combinator +, a technique I've used here:

li:not([attribute_name='a']) + li[attribute_name='a'], 
li:not([attribute_name='b']) + li[attribute_name='b']

As you can tell, if you have a lot of different possible values, your selector will grow very quickly. But it is the only real way to do this using pure CSS, and even then it still requires knowing the possible values in advance.

like image 60
BoltClock Avatar answered Dec 02 '25 03:12

BoltClock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!