Is there a selector for 2 or more elements with th

2020-02-07 05:40发布

问题:

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 + .standard.color-1,
.standard.color-2 + .standard.color-2,
.standard.color-3 + .standard.color-3,
.standard.color-4 + .standard.color-4,
.standard.color-5 + .standard.color-5,
.standard.color-6 + .standard.color-6,
.standard.color-7 + .standard.color-7,
.standard.color-8 + .standard.color-8 {
  padding-top: 0;
}

Is there perhaps some selector that checks for matches of the classes found on 2 or more elements without actually knowing the exact class's name? Such as something like:

.standard.color-* + .standard.color-* {
  padding-top: 0;
}

What I have currently (posted above) works the way I want it to as far as how it displays on my site, but I am just curious whether, or not, I am doomed to constantly add .standard.color-# + .standard.color-# for every new color I need (which in for this case are background-colors for full-width <section> tags).

Examples:

<section class="standard color-0"></section> // top and bottom padding
<section class="standard color-1"></section> // top and bottom padding

-----------------------------------------------------------------------

<section class="standard color-1"></section> // top and bottom padding
<section class="standard color-1"></section> // padding-top: 0; (if both "color-#" is the exact same this loses its top padding)

EDIT: Simplified post and code. <section> will always have a .standard class and a .color- class with .color-0 being background-color: transparent;.

回答1:

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.