如何选择仅包含"foobar"类的元素,不要选择它是否包含任何其他类?

tee*_*ane 21 html css css-selectors

我只想选择元素,如果它有一个类,那个类是'foobar'.

<style>
.foobar {
    /* only apply to an element if the element has a class and the only class is 'foobar'. */
    background: black;
    color: white;
}
</style>

<div class="foobar">i should be selected</div>

<div class="foobar ipsum">i should not be selected</div>
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过添加.foobar.ipsum {do one thing}和.foobar {something else}的样式来选择它,但我无法控制其他类.基本上当元素只有foobar类时,我知道它是我的元素并且来自其他地方.当CSS库世界发生碰撞时会发生这种情况.我知道这里有更深层次的问题要解决,但现在这让我很难过.

Bol*_*ock 39

使用纯CSS的最简单方法是使用属性选择器:

[class="foobar"] {
    /* only apply to an element if the element has a class and the only class is 'foobar'. */
    background: black;
    color: white;
}
Run Code Online (Sandbox Code Playgroud)

您可能无法控制其他元素,但如果您可以控制其他元素,并且可以修改其class属性,那么mayabelle就可以为您的元素分配自己的特殊类并选择该类进行选择.这样你明确说明哪个元素是你的,而不是假设没有额外的类意味着它是你的.


412*_*412 6

您将需要使用属性选择器:

[class="foobar"] {
    background: black;
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/dA2dp/