How to select element that contains only the class

2019-04-04 02:32发布

问题:

I only want to select the element if it has one class and that class is '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>

I know I could select it with adding a style for .foobar.ipsum { do one thing } and .foobar { something else } but I don't have control over the additional classes. Basically when the element has only the foobar class, I know it's my element and coming from somewhere else. This is what happens when CSS Library worlds collide. I know that there are deeper issues to resolve here but this is stumping me right now.

回答1:

The simplest way with pure CSS is to use an attribute selector:

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

You may not have control over the other elements, but if you have control over yours and you can modify its class attribute, mayabelle makes a good point about assigning your element its own special class and selecting by that class instead. That way you explicitly state which element is yours rather than going by the assumption that not having additional classes means it's yours.



回答2:

You will need to use an attribute selector:

[class="foobar"] {
    background: black;
}

http://jsfiddle.net/dA2dp/



回答3:

If it's "your element", can you apply an additional class to it? Then you can select using that:

<style>
.foobar.yourClass {
    /* your css */
}
</style>

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