如何选择仅包含"foobar"类的元素,而不选择是否包含其他任何类? [英] How to select element that contains only the class of "foobar", don't select if it contains any other classes?

查看:72
本文介绍了如何选择仅包含"foobar"类的元素,而不选择是否包含其他任何类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想选择具有一个类并且该类为'foobar'的元素.

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>

我知道我可以通过为.foobar.ipsum {做某事}和.foobar {其他事}添加样式来选择它,但是我无法控制其他类.基本上,当元素只有foobar类时,我知道它是我的元素并且来自其他地方. CSS库世界冲突时会发生这种情况.我知道这里有更深层次的问题需要解决,但这正困扰着我.

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.

推荐答案

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

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

您可能无法控制其他元素,但是如果您可以控制其他元素,则可以修改其class属性,

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.

这篇关于如何选择仅包含"foobar"类的元素,而不选择是否包含其他任何类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆