我只想选择具有一个类且该类为“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 { do one thing } 和 .foobar { something else } 添加样式来选择它,但我无法控制其他类。基本上当元素只有 foobar 类时,我知道它是我的元素并且来自其他地方。这就是 CSS 库世界发生碰撞时发生的情况。我知道这里有更深层次的问题需要解决,但这现在让我很困惑。
最佳答案
使用纯 CSS 的最简单方法是使用属性选择器:
[class="foobar"] {
/* only apply to an element if the element has a class and the only class is 'foobar'. */
background: black;
color: white;
}
您可能无法控制其他元素,但如果您可以控制您的元素并且可以修改其 class
属性,mayabelle makes a good point关于为您的元素分配自己的特殊类并改为按该类进行选择。这样您就可以明确说明哪个元素是您的,而不是假设没有其他类就意味着它是您的。
关于html - 如何选择仅包含 "foobar"类的元素,如果它包含任何其他类则不选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19547088/