Is there a selector for 2 or more elements with the same attribute value?
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;
}
Maybe some kind of selector that checks for matches of classes found on 2 or more elements without actually knowing the exact class name? For example, something like:
.standard.color-* + .standard.color-* {
padding-top: 0;
}
What I have (posted above) works the way I want, as far as it appears on my site, but I'm just wondering if not or not, I'm doomed to constantly add .standard.color-# + .standard.color-#
for every new color I need (for this case uses background colors for full-width tags <section>
).
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 class .standard
and class .color-
c .color-0
background-color: transparent;
.
source to share
Unfortunately, due to the static nature of selectors, CSS does not offer a way for one compound selector to refer to any part of another compound selector, even with regex syntax . Thus, you cannot, for example, match an element with the same class name or attribute value as its previous sibling without hard-coding the actual value in both compound selectors. The only solution is what you have.
As I mentioned in my answer to the question linked above, if you use a preprocessor, you can automate it. This will still result in the same hard-coded selectors in CSS, but the task of actually writing those selectors is dumped into 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 log all possible values ββ(or you don't want to), then you need to write a script to check the values ββat runtime.
source to share