使用CSS随机生成ID的元素 [英] Select elements with randomly-generated IDs with CSS
问题描述
我有这个标记,其中的id不是预先知道的:
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>
所有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; }
这可以在没有硬编码id的情况下使用!important
并更改HTML标记?
Could this be done without hard-coding ids, using !important
and changing HTML markup?
推荐答案
code>,您可能需要考虑使用:not()
伪类来增加选择器的特异性,如下所示:
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; }
这与原始选择器匹配相同的元素(假设 hack
不是产品div的可能ID,看起来很可能在这里),但由于:not()中的-class-increase-the-specificity-of-a-selector>选择器,
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!)
这篇关于使用CSS随机生成ID的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!