使用CSS随机生成ID的元素 [英] Select elements with randomly-generated IDs with CSS

查看:123
本文介绍了使用CSS随机生成ID的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个标记,其中的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.

(主要!important ,则不会使用是重载!important 规则的唯一方法是使用另一个 !important 规则,所以你使用它越多,你会发现自己需要它越多,最终,你的CSS规则的一半将被标记为!important 基本上回到你开始的地方,除了现在你的样式表膨胀了大量的!重要的标记,你也有效地剥夺了自己使用!important 可以在极少数情况下覆盖普通样式,这种情况下,它实际上是合法有用的,现在已经 使用像上面所示的特殊hacks。道德的故事:!important 是强大的,但容易滥用—不要使用它,除非你真的需要!)

(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆