Html 如何使用 CSS 专门针对此元素 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4654022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:05:03  来源:igfitidea点击:

How can I specifically target this element id with CSS?

htmlcsscss-selectorscss-specificity

提问by Damon

<div id=checkout>
<form id="confirmation" class="center">
<p>content</p>
</form>
</div>

I have a CSS selector #checkout form.centeralready being used

我有一个CSS选择器#checkout form.center已被使用

i would like to override this specifically for the confirmation form, but none of the things I try to write get applied. I should think that #confirmation form.centeror something should supercede the first rule, but it doesn't even seem to hit the target. #confirmationgets overridden by the above mentioned selector because it's not as specific.

我想专门为确认表格覆盖这一点,但我尝试编写的任何内容都没有得到应用。我应该认为#confirmation form.center应该取代第一条规则,但它似乎甚至没有达到目标。#confirmation被上面提到的选择器覆盖,因为它不是那么具体。

回答by Jon

Expanding on BoltClock's answer:

扩展 BoltClock 的回答:

Each CSS selector has a specificityvalue. For each element, in case of a conflict for the value of one of its properties, the rule with highest specificity takes precedence. Generally, the more and better information in a CSS selector, the greater its specificity.

每个 CSS 选择器都有一个特殊性值。对于每个元素,如果其属性之一的值发生冲突,则具有最高特异性的规则优先。一般来说,CSS 选择器中的信息越多越好,其特异性就越大。

For this reason, adding something appropriate to your existing selector (#checkout form.center) will enable you to override it:

出于这个原因,添加一些适合您现有选择器 ( #checkout form.center) 的内容将使您能够覆盖它:

#checkout form.center {
  /* your existing CSS */
}

#checkout #confirmation {
  /* your overrides; this has higher specificity */
}

#checkout form#confirmation {
  /* this would also work -- even higher specificity */
}

#checkout form#confirmation.center {
  /* even higher */
}

#checkout form.center p {
  /* works inside the p only, but also has
     greater specificity than #checkout form.center  */
}

回答by BoltClock

If you need to specifically override your existing selector, use:

如果您需要专门覆盖现有的选择器,请使用:

#checkout #confirmation

The reason why #confirmation form.centerdoesn't work is because that selects form.centerthat sits withina #confirmationelement, which isn't the same. You would have written it as this instead:

为什么之所以#confirmation form.center不起作用是因为选择form.center的是位于一个#confirmation元素,它是不一样的。你应该把它写成这样:

#checkout form#confirmation.center

but that's way overkill; the first selector I suggest is specific enough to override your first selector.

但这太过分了;我建议的第一个选择器足够具体,可以覆盖您的第一个选择器。