Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements with randomly-generated IDs with CSS

I have this markup where the ids are not known in advance:

#product-20625055 { background-color: #FC0; }
#product-66980342 { background-color: #0CF; }
#product-54722210 { background-color: #F0C; }
<div class="product" id="product-20625055">Product 1</div>
<div class="product" id="product-66980342">Product 2</div>
<div class="product" id="product-54722210">Product 3</div>

I need to change the background color of all divs. This is the most specific selector I could think of but it does not work:

div.product[id^="product-"] { background-color: transparent; }

Could this be done without hard-coding ids, using !important and changing HTML markup?

like image 915
Salman A Avatar asked Jan 28 '16 13:01

Salman A


2 Answers

Instead of resorting to !important, you might want to consider using the :not() pseudo-class to increase the specificity of your selector, like this:

div.product:not(#specificity-hack) { background-color: transparent; }

This matches the same elements as your original selector (assuming that specificity-hack is not a possible ID for a product div, which seems likely here), but since selectors inside :not() are included in the specificity calculation, it counts as more specific than the rules you're trying to override.

(The main reason not to use !important if you can avoid it is that it's addictive — the only way to override an !important rule is with another !important rule, so the more you use it, the more you'll find yourself needing it. Eventually, half your CSS rules will be marked !important, and you're basically back where you started, except that now your style sheets are bloated with lots of !important markers, and you've also effectively deprived yourself of the ability to use !important to override normal styles in the rare cases where it's actually legitimately useful, and now have to resort to specificity hacks like the one shown above. Moral of the story: !important is powerful but easy to abuse — don't use it unless you really have to!)

like image 196
Ilmari Karonen Avatar answered Oct 01 '22 22:10

Ilmari Karonen


I think this is one of those cases where !important might be the best option.

#product-20625055 {
  background-color: #FC0;
}
#product-66980342 {
  background-color: #0CF;
}
#product-54722210 {
  background-color: #F0C;
}
div[id^="product-"].product {
  background-color: transparent !important;
}
<div class="product" id="product-20625055">Product 1</div>
<div class="product" id="product-66980342">Product 2</div>
<div class="product" id="product-54722210">Product 3</div>
like image 20
Paulie_D Avatar answered Oct 01 '22 21:10

Paulie_D