CSS 如何选择“A”类而不是“B”类的div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2481414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do I select a div with class "A" but NOT with class "B"?
提问by MedicineMan
I have some divs:
我有一些 div:
<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>
Is there a CSS selector that will get me the div containing Target
but not the divs containing NotMyTarget
?
是否有一个 CSS 选择器可以让我获取包含Target
但不包含div的 div NotMyTarget
?
Solution must work on IE7, IE8, Safari, Chrome, and Firefox
解决方案必须适用于 IE7、IE8、Safari、Chrome 和 Firefox
Edit: 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 */
}
采纳答案by Ron DeVera
You can use the attribute selector to match the div
that has only one class:
您可以使用属性选择器来匹配div
只有一个类的 :
div[class=A] {
background: 1px solid #0f0;
}
If you want to select another div
that has multiple classes, use quotes:
如果要选择div
具有多个类的另一个,请使用引号:
div[class="A C"] {
background: 1px solid #00f;
}
Some browsers do not support the attribute selector syntax. As usual, "some browsers" is a euphemism for IE 6 and older.
某些浏览器不支持属性选择器语法。像往常一样,“某些浏览器”是 IE 6 及更早版本的委婉说法。
See also: http://www.quirksmode.org/css/selector_attribute.html
另见:http: //www.quirksmode.org/css/selector_attribute.html
Full example:
完整示例:
<!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>
EDIT 2014-02-21:Four years later, :not
is now widely available, though verbose in this specific case:
编辑 2014-02-21:四年后,:not
现已广泛使用,但在这种特定情况下很冗长:
.A:not(.B):not(.C):not(.D):not(.E) {
border: 1px solid red;
}
Unfortunately, this doesn't work in IE 7–8 as specified in the question: http://caniuse.com/#search=:not
不幸的是,这在问题中指定的 IE 7–8 中不起作用:http: //caniuse.com/#search=:not
回答by Ms2ger
.A:not(.B) {}
But guess who doesn't support that... Indeed, IE<=8.
但是猜猜谁不支持...确实,IE<=8。
回答by Nick Craver
I think the best you can do (until CSS 3) is override the styles in this case with what you don't want from class A B
in A
, like this:
我认为你能做的最好的事情(直到 CSS 3)是在这种情况下用你不想要的 class A B
in覆盖样式A
,像这样:
.A.B { /* Styles */ }
.A { /* Reverse any styling you don't want */ }