CSS选择紧挨在具有不同属性值的元素之后放置的所有元素 [英] CSS selecting all elements that are placed immediately after an element with a different attribute value

查看:156
本文介绍了CSS选择紧挨在具有不同属性值的元素之后放置的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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>

我只想选择第三个< li> 。属性名称是固定的,但其值是动态的,并且不会预先知道。 < li> 的数量也是动态的。

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?

推荐答案

是否有解决方案取决于你的标记。

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

因为选择器大多是静态的,没有变量,所以没有办法使用选择器来匹配具有基于另一个元素(或缺少它)的特定属性值的任何元素。相同的属性值,不提前知道该值。如果此属性的可能值无法确定,则不存在纯CSS解决方案。

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.

如果此属性仅存在一组有限的值,并且您知道这些值事先,你可以为每个可能的值写一个选择器,但你需要硬编码每一个值。这样的选择器将使用:not()伪类与相邻同级组合器 + 我使用了一种技术这里

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']


b $ b

你可以知道,如果你有很多不同的可能值,你的选择器将增长非常快。但是它是使用纯CSS做到这一点的唯一真正的方法,即使它仍然需要提前知道可能的值。

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.

这篇关于CSS选择紧挨在具有不同属性值的元素之后放置的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆