CSS:应用于类组合的样式?
我不确定这是否可行,但是当您想根据应用于元素的类的组合来设置元素的样式时,是否可以在 CSS 中使用语法?
我知道我可以使用 jQuery 或其他东西检查元素并根据它所具有的类更改它的样式,但是有没有一种纯 CSS 方法可以做到这一点?
例如,如果我有一个粗体和绿色的类:
.bold_green { color:green; font-weight:bold; }
和一个粗体和蓝色的类:
.bold_blue { color:blue; font-weight:bold. }
现在,假设我正在使用 jQuery 动态添加和删除类,并希望具有这两个类的任何元素都变为斜体粉红色。
比如:
.bold_green AND .bold_blue { color:pink; font-style:italic; }
或者,如果我想设计一个具有类的元素,并且是具有另一个类的另一个元素的后代?
比如:
.bold_green HAS_CHILD .bold_blue { color:black; background-color:yellow; }
谢谢!
编辑
感谢您的所有回答。这些几乎就是我的想法(只是将类视为常规选择器),但它们似乎对我不起作用。我必须检查我的代码并确保它们不会以某种方式被覆盖......
I'm not sure this is possible, but is there a syntax to be used in CSS when you want to style an element based on the combination of classes applied to it?
I understand that I can check an element with jQuery or something and change it's style based on the classes it has, but is there a pure CSS way to do this?
For example, if I have a class for bold and green:
.bold_green { color:green; font-weight:bold; }
And a class for bold and blue:
.bold_blue { color:blue; font-weight:bold. }
Now, say I am using jQuery to add and remove classes dynamically and want any element that has both classes to turn italic pink.
Something like:
.bold_green AND .bold_blue { color:pink; font-style:italic; }
Or, if I want to style an element that has aclass, and is a descendant of another element that has another class?
Something like:
.bold_green HAS_CHILD .bold_blue { color:black; background-color:yellow; }
Thanks!
Edit
Thanks for all the answers. These are pretty much what I thought (just treating the classes as regular selectors), but they don't seem to be working for me. I will have to check my code and make sure they aren't being overridden somehow...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
或者在 CSS 中:
注意选择器之间没有空格。
Or in CSS:
Notice there's no space between the selectors.
你不需要任何特别的东西,只需
You don't need anything special, just
保罗和Voyager 对于多类情况是正确的。
对于“HAS CHILD”情况,您将使用:
这将为
bold_green
元素内的任何bold_blue
元素设置样式。或者,如果您想要一个直接子级:
它将仅设置具有直接父级
bold_green
的bold_blue
元素的样式。Paul and Voyager are correct for the multiple classes case.
For the "HAS CHILD" case you would use:
Which will style any
bold_blue
elements inside abold_green
element.Or if you wanted a DIRECT child:
Which will style only
bold_blue
elements which have an immediate parentbold_green
.在 Visual Studio 2013 中,CSS 设置通过“逗号”应用于多个类,如下所示:
.bold_green, .bold_blue { color:pink;字体样式:斜体; }
In visual studio 2013 the CSS setting is applied to multiple classes by a "Comma" as follows:
.bold_green, .bold_blue { color:pink; font-style:italic; }