Is there a selector for 2 or more elements with the same attribute value?

后端 未结 1 832
鱼传尺愫
鱼传尺愫 2020-12-11 23:12

Is there a more elegant way to write this?

.standard {
  padding-top: 50px;
  padding-bottom: 50px;
}
.standard.color-0 + .standard.color-0,
.standard.color-         


        
相关标签:
1条回答
  • 2020-12-11 23:52

    Unfortunately, due to the static nature of selectors, CSS doesn't offer a way for one compound selector to reference any part of another compound selector, not even with a regex-like syntax. So you can't, for example, match an element with the same class name or attribute value as its previous sibling without hardcoding the actual value, in both compound selectors. The only solution is the one you have.

    As I mention in my answer to the question linked above, if you're using a preprocessor, you can automate this somewhat. It will still result in the same hardcoded selectors in CSS, but the task of actually writing those selectors is offloaded to the preprocessor instead. Here's an example using SCSS:

    .standard {
      padding-top: 50px;
      padding-bottom: 50px;
    
      &%consecutive {
        padding-top: 0;
      }
    
      // To accommodate more numbered classes simply edit this loop
      @for $i from 0 through 8 {
        &.color-#{$i} + &.color-#{$i} {
          @extend %consecutive;
        }
      }
    }
    

    This, again, requires knowing the values in advance. If you cannot write down all the possible values (or you don't want to), you'll need to write a script to examine the values in runtime.

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