CSS selecting all elements that are placed immediately after an element with a different attribute value

前端 未结 2 813
说谎
说谎 2021-01-26 17:01

HTML:

  • Test
  • Test
  • Test
相关标签:
2条回答
  • 2021-01-26 17:59

    I think this can be accomplished by using the nth-child() Selector:

    p:nth-child(2)
    {
     background:#ff0000;
    }
    

    http://jsfiddle.net/davekerr/94Cgt/

    0 讨论(0)
  • 2021-01-26 18:05

    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.

    0 讨论(0)
提交回复
热议问题