仅当存在 2 个类时,您才能使用 CSS 定位元素吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/640996/
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
Can you target an element with CSS only if 2 classes are present?
提问by alex
As you probably already know, you may have multiple classes on elements separated by a space.
您可能已经知道,您可能在由空格分隔的元素上有多个类。
Example
例子
<div class="content main"></div>
And with CSS you can target that div
with either .content
or .main
. Is there a way to target it if and only ifboth classes are present?
使用 CSS,您可以div
使用.content
或来定位它.main
。当且仅当两个类都存在时,有没有办法定位它?
Example
例子
<div class="content main">I want this div</div>
<div class="content">I don't care about this one</div>
<div class="main">I don't want this</div>
Which CSS selector would I use to get the first div
only (assume I can't use .content:first-child
or similar)?
我将使用哪个 CSS 选择器来获得第一个div
(假设我不能使用.content:first-child
或类似的)?
回答by Gumbo
Yes, just concatenate them: .content.main
. See CSS class selector.
是的,只要将它们连接起来:.content.main
。请参阅CSS 类选择器。
But note that the Internet Explorer up to version 6 doesn't support multiple class selectors and just honors the last class name.
但请注意,版本 6 之前的 Internet Explorer 不支持多个类选择器,只支持最后一个类名。
回答by Wesley Murch
Just for the sake of it (I don't really recommend you do this), there isanother way to do it:
只是为了它的缘故(我真的不建议你这样做),有是另一种方式来做到这一点:
.content[class~="main"] {}
Or:
或者:
.main[class~="content"] {}
Reference: http://www.w3.org/TR/CSS2/selector.html
参考:http: //www.w3.org/TR/CSS2/selector.html
E[foo~="warning"] Matches any E element whose "foo" attribute value is a list of space-separated values, one of which is exactly equal to "warning"
E[foo~="warning"] 匹配任何 E 元素,其 "foo" 属性值为空格分隔值列表,其中一个值完全等于 "warning"
Demo: http://jsfiddle.net/eXrSg/
演示:http: //jsfiddle.net/eXrSg/
Why this is actually useful (for IE6 at least):
为什么这实际上很有用(至少对于 IE6):
Since IE6 does not support multiple classes, we can't use .content.main
, butthere are some javascript libraries like IE-7.jsthat enable the attribute selector, but still seem to fail when it comes to multiple classes. I have tested this workaround in IE6 with javascript enabling the attribute selector, and it is ugly, but it works.
由于 IE6 不支持多类,我们不能使用.content.main
,但是有一些像IE-7.js这样的javascript 库启用了属性选择器,但是当涉及到多类时似乎仍然失败。我已经在 IE6 中使用启用属性选择器的 javascript 测试了这个解决方法,它很难看,但它有效。
I have yet to find a script that makes IE6 support multiple class selectors but have found many that enable attribute selectors. If someone knows of one that works, please give me a shout in the comments so I can be rid of this workaround.
我还没有找到使 IE6 支持多个类选择器的脚本,但已经找到了许多启用属性选择器的脚本。如果有人知道一个有效的方法,请在评论中告诉我,这样我就可以摆脱这种解决方法。