关于令人困惑的 CSS 特异性规则的问题(摘自《SAMS Teach Yourself CSS in 24 Hours Second Ed》一书)
这是本书给出的关于浏览器如何确定在冲突中应用哪条规则的 5 条规则中的第 2 条:
id 选择器是第二个最具体的[在内联样式属性之后]。如果规则中存在多个 id,则 id 选择器数量最多的规则获胜。
我真的不明白规则 2 在说什么——它说“如果规则中存在多个 id”(这是单数)。如果只有一条规则,如何存在冲突或比较(“最大……的规则获胜”)?一条规则怎么会有不同数量的 id 选择器,如果只有一条规则,冲突在哪里?
有人可以彻底解释一下这条规则吗?感谢您的帮助,因为我正在努力了解网页设计的基础知识
This is Rule 2 of 5 rules the book gives about how the browser determines which rule to apply in a conflict:
An id selector is the second most specific [after inline style attribute]. If there is more than one id in the rule, the rule with greatest number of id selectors wins.
I really don’t understand what Rule 2 is talking about – it says “if there is more than one id in the rule” (which is singular). If there is only one rule, how is there a conflict or comparison(“the rule with greatest… wins”)? How can one rule have a differing number of id selectors, and where is the conflict if there is only one rule?
Can someone please expain this rule thoroughly? Thanks for helping, as I am trying to get the basics of web design down
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个选择器可以有任意数量的 ID 选择器。
例如,如果 ID 为
id2
的元素是 ID 为id1
的元素的后代,#id1 #id2
会选择该元素。它有两个 ID 选择器,因此它比#id2
更具体,后者只选择任何具有 IDid2
的元素,没有任何其他条件。因此,在这两个规则之间(假设没有内联样式):
第一个规则优先,并且该元素中的文本颜色为红色而不是蓝色,因为第一个规则具有更多 ID 选择器。
A selector may have any number of ID selectors.
For example,
#id1 #id2
selects the element with the IDid2
if it's a descendant of the element with the IDid1
. It has two ID selectors, so it'll be more specific than, say,#id2
, which just picks any element as long as it's the one with the IDid2
, without any other conditions.So between these two rules (assuming no inline styles):
The first rule takes precedence, and the text in that element is colored red rather than blue, because the first rule has more ID selectors.
这是一个示例,具有更多 id 的选择器将优先:
现在,当我应用 css 时,
选择器
#parent #child
将优先。因为它比第二个更具体。在这种情况下,div 将具有红色背景。Here is an example, the selector with more id will take precedence:
now when i apply the css
the selector
#parent #child
will take precedence. because it is more specific than the second one. in this case the div will have a red background.