您是否有理由在 CSS 中声明带有 ID 的 HTML 选择器?
原始版本的编辑版本
声明 div#test
与仅将其声明为 #test
有何不同?我也可以在同一个样式表中声明这两个样式,即
#div test {
}
#test {
}
原始问题
如果我要声明以下样式 div#test
这与引用 div 有什么不同带有 ID
元素,例如 test
的content
EDIT
澄清什么我的意思是,怎么样div#test
与 #test
不同,然后在 div
元素中引用它。
Edited version of the original
How is declaring div#test
different to declaring it as just #test
? Also can I declare both of the in the same stylesheet i.e.
#div test {
}
#test {
}
Original question
If I were to declare the following style div#test
how is that different to referencing a div
element with an ID test
e.g. <div id="test">content</div>
EDIT
To clarify what I mean is that how is div#test
different to just #test
and then referencing it in the div
element.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果每个页面都有全局 css,并且在一个页面上将 #test 添加到 div 元素,而在其他页面上为 p 添加它,那么这是有意义的。在这种情况下,即使 p 具有 id #test,如果使用 div#test 而不是 #test,CSS 规则也不会应用于它。
然而,您可能应该考虑重命名这些冲突的元素,但并不总是可能的(例如,您不是唯一使用 html 和 css 或某些外部插件等的人)。当然,这不是很好的保护,但在某些特定情况下仍然有意义。
it makes a sense if you have global css for every page and on one page you add #test to div element and on some other page you add it for p. in such case, even though p has id #test, css rules will not be applied to it if div#test is used instead of #test.
however probably you should consider renaming such conflicting elements, but not always it is possible (for example you are not the only one who works with html and css or some external plugins, whatever). of course it is not good protection, but still, could make sense in some specific cases.
因为 id 必须是唯一的。尽管在外部样式表中,它可以让读者知道其适用的元素类型。
as id must be unique nothing. although in an external stylesheet it may allow readers to know the type of element this applies to.
如果你在 css 中使用 div#test ,它会查找属于 div 且名为 test 的任何 ID,就像你刚刚执行了 #test 一样,它可以应用于任何其他元素。它还增加了您的选择的特异性,并可能帮助那些审查您的代码的人确切地知道您所指的内容。
示例。
希望这会有所帮助。
If you use div#test in your css, it will look for any ID with the name test, that belongs to a div, as if you just did #test, it could be applied to any other element. It also add's specificity to your selection, and could potentially help those reviewing your code know exactly what you are referring to.
Example.
Hope this helps.