只有当两个类出现时,你才能用 CSS 来定位一个元素吗?

正如您可能已经知道的那样,您可能在由空格分隔的元素上有多个类。

例子

<div class="content main"></div>

通过 CSS,你可以使用 .content或者 .main来定位 div。如果 除非两个类都存在,有没有办法瞄准它?

例子

<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>

我将使用哪个 CSS 选择器来获得第一个 div(假设我不能使用 .content:first-child或类似的) ?

55286 次浏览

Yes, just concatenate them: .content.main. See CSS class selector.

But note that the Internet Explorer up to version 6 doesn’t support multiple class selectors and just honors the last class name.

Just for the sake of it (I don't really recommend you do this), there is another way to do it:

.content[class~="main"] {}

Or:

.main[class~="content"] {}

Reference: 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"

Demo: http://jsfiddle.net/eXrSg/

Why this is actually useful (for IE6 at least):

Since IE6 does not support multiple classes, we can't use .content.main, but there are some javascript libraries like IE-7.js that 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.

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.