在另一个类中调用 CSS 类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6327198/
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
Calling a CSS class inside another class?
提问by Abhishek
Is it possible to have one CSS class reference another? Instead of rewriting all the css code again?
是否可以让一个 CSS 类引用另一个?而不是再次重写所有 css 代码?
For example, I have this:
例如,我有这个:
.btn{
/* Whatever btn related styles I have */
}
.btn:hover{
box-shadow:0 0 4px black;
}
.btn:active{
/* This is where I want to reference the '.red' class */
}
.red{
/* There is a LOT of CSS code here for cross browser gradients */
}
The thing is, I'm already using the .red class as is in certain places, and I'd also like to apply the same gradient style to the 'active' state of all elements with the .btn class...
问题是,我已经在某些地方使用了 .red 类,而且我还想将相同的渐变样式应用于 .btn 类的所有元素的“活动”状态......
If you can help solve (it need not be the way I've requested it) this, I'd greatly appreciate it...
如果你能帮助解决(不一定是我要求的方式)这个,我将不胜感激......
采纳答案by T.J. Crowder
You can't actually do a reference (one of CSS's major failings), but you can do this:
你实际上不能做参考(CSS 的主要失败之一),但你可以这样做:
.btn:active, .red {
/* Block A: Most (or all) of what used to just be in .red below */
}
.btn:active {
/* Block B: Stuff *just* for .btn:active, if any */
}
.red {
/* Block C: Stuff *just* for .red, if any */
}
The comma means that the definitions in the body of Block A apply separately to eachof those selectors, and so they apply to any ".btn" elements that are ":active", and separately apply to any ".red" elements.
逗号意味着块 A 主体中的定义分别适用于这些选择器中的每一个,因此它们适用于任何 ":active" 的 ".btn" 元素,并分别适用于任何 ".red" 元素。
Block B and Block C are optional. They're for any definitions you only want to apply to the given selector. You usually list these afterBlock A because rules of equal specificity are applied top-to-bottom, so you can override anything from Block A that you want to in Block B or Block C, and those blocks will "win".
B 块和 C 块是可选的。它们适用于您只想应用于给定选择器的任何定义。您通常将它们列在A 块之后,因为从上到下应用了相同的特异性规则,因此您可以覆盖 A 块中想要在 B 块或 C 块中覆盖的任何内容,这些块将“获胜”。