如何选择类别为"A"的div但不是"B"类? [英] how do I select a div with class "A" but NOT with class "B"?
问题描述
我有一些divs
<div class="A">"Target"</div>
<div class="A B">"NotMyTarget"</div>
<div class="A C">"NotMyTarget"</div>
<div class="A D">"NotMyTarget"</div>
<div class="A E">"NotMyTarget"</div>
有没有CSS选择器,可以让我得到包含Target
的div但不能得到包含NotMyTarget
的div?
Is there a CSS selector that will get me the div containing Target
but not the divs containing NotMyTarget
?
解决方案必须能够在IE7,IE8,Safari,Chrome和Firefox上运行
Solution must work on IE7, IE8, Safari, Chrome, and Firefox
到目前为止,尼克是最接近的.这很笨拙,我不喜欢该解决方案,但至少它能起作用:
So far Nick is the closest. It's clumsy and I don't like the solution, but at least it works:
.A
{
/* style that all divs will take */
}
div.B
{
/* style that will override style .A */
}
推荐答案
您可以使用属性选择器来匹配只有一个类的div
:
You can use the attribute selector to match the div
that has only one class:
div[class=A] {
background: 1px solid #0f0;
}
如果要选择另一个具有多个类的div
,请使用引号:
If you want to select another div
that has multiple classes, use quotes:
div[class="A C"] {
background: 1px solid #00f;
}
某些浏览器不支持属性选择器语法.与往常一样,某些浏览器"是IE 6及更早版本的委婉说法.
Some browsers do not support the attribute selector syntax. As usual, "some browsers" is a euphemism for IE 6 and older.
另请参见: http://www.quirksmode.org/css/selector_attribute.html
完整示例:
<!DOCTYPE html>
<html>
<head>
<style>
.A { font-size:22px; }
.B { font-weight: bold; border: 1px solid blue; }
.C { color: green; }
div[class="A"] {
border: 1px solid red;
}
div[class="A B"] {
border: 3px solid green;
}
</style>
</head>
<body>
<div class="A">"Target"</div>
<div class="A B">"NotMyTarget"</div>
<div class="A C">"NotMyTarget"</div>
<div class="A D">"NotMyTarget"</div>
<div class="A E">"NotMyTarget"</div>
</body>
</html>
编辑2014-02-21:四年后,:not
现已广泛使用,尽管在这种特定情况下很冗长:
EDIT 2014-02-21: Four years later, :not
is now widely available, though verbose in this specific case:
.A:not(.B):not(.C):not(.D):not(.E) {
border: 1px solid red;
}
不幸的是,这在问题7中指定的IE 7-8中不起作用: http://caniuse.com/#search=:not
Unfortunately, this doesn't work in IE 7–8 as specified in the question: http://caniuse.com/#search=:not
这篇关于如何选择类别为"A"的div但不是"B"类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!