How to do not apply CSS on a specific TAG
I do not know if is possible in CS开发者_开发技巧S, but I would like a general Role to don't apply to a specific element in my case id=special
.
In my example all the DIV should be red but I want only id=special
to have not applied this color.
I understand I can always overwrite the element with id=special
but I'm interested to know if is possible have some sort of exclusion from the general Role.
Any idea in CSS 2 and CSS 3?
Example:
<div>this is red</div>
<div>this is red</div>
<div id="special">this one must be blus</div>
div>this is red</div>
// My General Role
div
{
background-color:Red;
}
CSS3 allows for the :not()
selector:
div:not([id])
-or-
div:not(#special)
depending on what you want to exclude
You can read all about the selectors in the w3c docs.
As for CSS2, there's a limited set of selectors, and they don't account for negation.
CSS2 Solution
div {
color: red;
}
div#special {
color: inherit;
}
demo: http://jsfiddle.net/zRxWW/1/
CSS3 solution:
div:not(#special)
You would want to use div:not(#special)
, but if it's going to be blue anyways then you might as well just override the rule. The :not()
selector is a CSS3 property and thus isn't supported by all browsers.
This is a great example of how CSS specificity works. A general rule applying to all elements of a certain type (your div
rule turning the background red) is superseded by the more specific rule applying to an ID. This concept has existed since CSS1, and is available in all browsers. Thus:
div {
background-color:red;
}
#special {
background-color: blue;
}
... will leave all divs red. By applying the special
id to a div, that one div will be blue instead.
See it in action: http://jsfiddle.net/9Hyas/
Check out these articles for more about CSS specificity: http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/ and http://www.htmldog.com/guides/cssadvanced/specificity/
精彩评论