添加不那么具体的类而不使用 !important
我有以下 CSS 规则:
.bookItem:hover { background: rgba(0,150,255,0.1); }
.selected { background: rgba(0,150,255,0.2) !important; }
单击 bookItem 时,我使用 jQuery 将选定的类添加到其中。问题是,如果没有 !important
,选定的类不会显示,直到鼠标不再悬停。我知道这是因为 :hover 伪类使这个选择器“更具体”。
是否可以更改 .selected
类,使其优先级高于 :bookItem:hover 而不 !important
?
I have the following CSS rules:
.bookItem:hover { background: rgba(0,150,255,0.1); }
.selected { background: rgba(0,150,255,0.2) !important; }
When a bookItem is clicked, I use jQuery to add the selected class to it. The trouble is, without the !important
the selected class does not show until the mouse is no longer hovering. I know this is because the :hover pseudoclass makes this selector "more specific".
Is it possible to change the .selected
class to cause it to take higher precedence than :bookItem:hover without the !important
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,在我看来,你应该重新考虑使用这个 css 关键字。 !important 是一个太强大的工具,它主要破坏了 css 的所有层次结构,使得调试代码变得非常困难。在没有办法的情况下,它的使用应该限制在少数极端的例子中。
同样,在我看来,您应该尝试使用尽可能多的 html 标签,然后使用类和 ids,最后使用 css 的特定属性。我会像我的同事建议的那样选择组合课程:
最后,有关其他信息,您可以阅读 粉碎杂志上的这篇文章
Well, in my opinion, you should reconsider using this css keyword at all. !important is a tool too powerful and it mainly destroys all the hierarchy css has, making it very difficult to debug your code. Its usage should be restricted to a small number of extreme examples when there is no way out.
Again, in my opinion, you should try to use as many html tags as possible, then use classes and ids, and lastly the specific atributes on css. I would go with the composed class like my fellows suggested:
Finally, for additional information, you can read this post at smashing magazine
我建议将
.selected
的特异性更改为.bookItem.selected
Demo: http://jsfiddle.net/WK34y/
I would suggest to change the specificity of
.selected
to.bookItem.selected
Demo: http://jsfiddle.net/WK34y/
使
.selected
类更通用,这样它就可以出现在任何地方,而不仅仅是在.bookItem
元素上,它对我强制使用.selected
样式很有用悬停时一个工作示例
to make
.selected
class more general so it can be anywhere and not only on.bookItem
elements, it worked for me forcing the.selected
style on hovera working example
这是一个特殊性的问题。在样式表中定义 .selected 像这样
http://css-tricks.com/ 855-具体-on-css-特异性/
This is a problem of specificity. In you stylesheet define .selected like this
http://css-tricks.com/855-specifics-on-css-specificity/